mlw_typing.ml 68.3 KB
Newer Older
1 2
(**************************************************************************)
(*                                                                        *)
MARCHE Claude's avatar
MARCHE Claude committed
3
(*  Copyright (C) 2010-2012                                               *)
4 5 6
(*    François Bobot                                                      *)
(*    Jean-Christophe Filliâtre                                           *)
(*    Claude Marché                                                       *)
MARCHE Claude's avatar
MARCHE Claude committed
7
(*    Guillaume Melquiond                                                 *)
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
(*    Andrei Paskevich                                                    *)
(*                                                                        *)
(*  This software is free software; you can redistribute it and/or        *)
(*  modify it under the terms of the GNU Library General Public           *)
(*  License version 2.1, with the special exception on linking            *)
(*  described in file LICENSE.                                            *)
(*                                                                        *)
(*  This software is distributed in the hope that it will be useful,      *)
(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)
(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                  *)
(*                                                                        *)
(**************************************************************************)

open Why3
open Util
23
open Ident
24 25 26
open Ty
open Term
open Decl
27 28 29
open Theory
open Env
open Ptree
30
open Mlw_dtree
31
open Mlw_ty
32
open Mlw_ty.T
33 34
open Mlw_expr
open Mlw_decl
35
open Mlw_pretty
36
open Mlw_module
Andrei Paskevich's avatar
Andrei Paskevich committed
37
open Mlw_wp
38
open Mlw_dty
39

40 41
(** errors *)

42
exception DuplicateProgVar of string
43 44 45 46 47 48 49 50 51 52 53
exception DuplicateTypeVar of string
(*
exception PredicateExpected
exception TermExpected
exception FSymExpected of lsymbol
exception PSymExpected of lsymbol
exception ClashTheory of string
exception UnboundTheory of qualid
exception UnboundType of string list
*)
exception UnboundTypeVar of string
54
exception UnboundSymbol of qualid
55 56 57 58

let error = Loc.error
let errorm = Loc.errorm

59 60
let qloc = Typing.qloc
let print_qualid = Typing.print_qualid
61 62 63

let () = Exn_printer.register (fun fmt e -> match e with
  | DuplicateTypeVar s ->
64 65 66
      Format.fprintf fmt "Type parameter %s is used twice" s
  | DuplicateProgVar s ->
      Format.fprintf fmt "Parameter %s is used twice" s
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
(*
  | PredicateExpected ->
      Format.fprintf fmt "syntax error: predicate expected"
  | TermExpected ->
      Format.fprintf fmt "syntax error: term expected"
  | FSymExpected ls ->
      Format.fprintf fmt "%a is not a function symbol" Pretty.print_ls ls
  | PSymExpected ls ->
      Format.fprintf fmt "%a is not a predicate symbol" Pretty.print_ls ls
  | ClashTheory s ->
      Format.fprintf fmt "Clash with previous theory %s" s
  | UnboundTheory q ->
      Format.fprintf fmt "unbound theory %a" print_qualid q
  | UnboundType sl ->
      Format.fprintf fmt "Unbound type '%a'"
        (Pp.print_list Pp.dot Pp.pp_print_string) sl
*)
  | UnboundTypeVar s ->
85 86 87
      Format.fprintf fmt "Unbound type variable '%s" s
  | UnboundSymbol q ->
      Format.fprintf fmt "Unbound symbol '%a'" print_qualid q
88 89 90 91
  | _ -> raise e)

(* TODO: let type_only = Debug.test_flag Typing.debug_type_only in *)

92 93
type denv = {
  uc     : module_uc;
94
  locals : (tvars * dvty) Mstr.t;
95
  tvars  : tvars;
Andrei Paskevich's avatar
Andrei Paskevich committed
96
  uloc   : Ptree.loc option;
97
}
98

99 100 101 102
let create_denv uc = {
  uc     = uc;
  locals = Mstr.empty;
  tvars  = empty_tvars;
Andrei Paskevich's avatar
Andrei Paskevich committed
103
  uloc   = None;
104
}
105

106 107 108 109 110 111
(* Handle tuple symbols *)

let ht_tuple   = Hashtbl.create 3
let ts_tuple n = Hashtbl.replace ht_tuple n (); ts_tuple n
let fs_tuple n = Hashtbl.replace ht_tuple n (); fs_tuple n

112
let check_at f0 =
Andrei Paskevich's avatar
Andrei Paskevich committed
113 114 115 116 117 118 119 120 121 122 123 124
  let rec check f = match f.t_node with
    | Term.Tapp (ls, _) when ls_equal ls fs_at ->
        let d = Mvs.set_diff f.t_vars f0.t_vars in
        if not (Mvs.is_empty d) then errorm ?loc:f.t_loc
          "locally bound variable %a under `at'"
          Pretty.print_vs (fst (Mvs.choose d))
        else true
    | _ ->
        t_all check f
  in
  ignore (check f0)

125 126 127 128 129 130
let count_term_tuples t =
  let syms_ts _ ts = match is_ts_tuple_id ts.ts_name with
    | Some n -> Hashtbl.replace ht_tuple n () | _ -> () in
  let syms_ty _ ty = ty_s_fold syms_ts () ty in
  t_s_fold syms_ty (fun _ _ -> ()) () t

131
let flush_tuples uc =
132 133 134 135 136 137
  let kn = Theory.get_known (get_theory uc) in
  let add_tuple n _ uc =
    if Mid.mem (ts_tuple n).ts_name kn then uc
    else use_export_theory uc (tuple_theory n) in
  let uc = Hashtbl.fold add_tuple ht_tuple uc in
  Hashtbl.clear ht_tuple;
138 139
  uc

140
let add_pdecl_with_tuples ~wp uc pd = add_pdecl ~wp (flush_tuples uc) pd
141
let add_decl_with_tuples uc d = add_decl (flush_tuples uc) d
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
(** Namespace lookup *)

let uc_find_ls uc p =
  let x = Typing.string_list_of_qualid [] p in
  try ns_find_ls (Theory.get_namespace (get_theory uc)) x
  with Not_found -> error ~loc:(qloc p) (UnboundSymbol p)

let uc_find_ts uc p =
  let x = Typing.string_list_of_qualid [] p in
  try ns_find_ts (get_namespace uc) x
  with Not_found -> error ~loc:(qloc p) (UnboundSymbol p)

let uc_find_ps uc p =
  let x = Typing.string_list_of_qualid [] p in
  try ns_find_ps (get_namespace uc) x
  with Not_found -> error ~loc:(qloc p) (UnboundSymbol p)

160 161
(** Typing type expressions *)

162
let rec dity_of_pty denv = function
163 164 165
  | Ptree.PPTtyvar id ->
      create_user_type_variable id
  | Ptree.PPTtyapp (pl, p) ->
166
      let dl = List.map (dity_of_pty denv) pl in
167
      begin match uc_find_ts denv.uc p with
168
        | PT ts -> its_app ts dl
169
        | TS ts -> ts_app ts dl
170 171
      end
  | Ptree.PPTtuple pl ->
172
      let dl = List.map (dity_of_pty denv) pl in
173
      ts_app (ts_tuple (List.length pl)) dl
174 175 176

(** Typing program expressions *)

Andrei Paskevich's avatar
Andrei Paskevich committed
177
let dity_int  = ts_app ts_int  []
178
let dity_real = ts_app ts_real []
179
let dity_bool = ts_app ts_bool []
Andrei Paskevich's avatar
Andrei Paskevich committed
180
let dity_unit = ts_app ts_unit []
181
(* dead code
Andrei Paskevich's avatar
Andrei Paskevich committed
182
let dity_mark = ts_app ts_mark []
183
*)
184

185
let unify_loc unify_fn loc x1 x2 = try unify_fn x1 x2 with
186
  | TypeMismatch (ity1,ity2) -> errorm ~loc
187 188 189
      "This expression has type %a, but is expected to have type %a"
      Mlw_pretty.print_ity ity2 Mlw_pretty.print_ity ity1
  | exn -> error ~loc exn
190

191 192 193 194 195 196 197
let expected_type { de_loc = loc ; de_type = (argl,res) } dity =
  if argl <> [] then errorm ~loc "This expression is not a first-order value";
  unify_loc unify loc dity res

let expected_type_weak { de_loc = loc ; de_type = (argl,res) } dity =
  if argl <> [] then errorm ~loc "This expression is not a first-order value";
  unify_loc unify_weak loc dity res
198

199
let rec extract_labels labs loc e = match e.Ptree.expr_desc with
200
  | Ptree.Enamed (Ptree.Lstr s, e) -> extract_labels (Slab.add s labs) loc e
201 202 203 204
  | Ptree.Enamed (Ptree.Lpos p, e) -> extract_labels labs (Some p) e
  | Ptree.Ecast  (e, ty) ->
      let labs, loc, d = extract_labels labs loc e in
      labs, loc, Ptree.Ecast ({ e with Ptree.expr_desc = d }, ty)
205
  | e -> labs, loc, e
206

207 208 209
let rec decompose_app args e = match e.Ptree.expr_desc with
  | Eapply (e1, e2) -> decompose_app (e2 :: args) e1
  | _ -> e, args
210

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
(* record parsing *)

let parse_record uc fll =
  let pl = match fll with
    | [] -> raise EmptyRecord
    | (pl,_)::_ -> pl in
  let its = match pl.pl_args with
    | [{ vtv_ity = { ity_node = Ityapp (its,_,_) }}] -> its
    | _ -> raise (BadRecordField pl.pl_ls) in
  let cs, pjl = match find_constructors (get_known uc) its with
    | [cs,pjl] -> cs, List.map (exn_option (BadRecordField pl.pl_ls)) pjl
    | _ -> raise (BadRecordField pl.pl_ls) in
  let pjs = List.fold_left (fun s pj -> Sls.add pj.pl_ls s) Sls.empty pjl in
  let flm = List.fold_left (fun m (pj,v) -> let pj = pj.pl_ls in
    if not (Sls.mem pj pjs) then raise (BadRecordField pj) else
      Mls.add_new (DuplicateRecordField (cs.pl_ls,pj)) pj v m)
    Mls.empty fll
  in
  cs,pjl,flm

231 232
let find_prog_field uc (p,e) = match uc_find_ps uc p with PL pl -> pl, e
  | _ -> errorm ~loc:(qloc p) "'%a' is not a record field" print_qualid p
233

234
let find_pure_field uc (p,e) = uc_find_ls uc p, e
235

236 237
let is_pure_record uc = function
  | fl :: _ -> (try ignore (find_prog_field uc fl); false with _ -> true)
238
  | [] -> raise Decl.EmptyRecord
239 240

let hidden_pl ~loc pl =
241 242
  { de_desc = DEglobal_pl pl;
    de_type = specialize_plsymbol pl;
243
    de_loc  = loc; de_lab = Slab.empty }
244 245

let hidden_ls ~loc ls =
246 247
  { de_desc = DEglobal_ls ls;
    de_type = specialize_lsymbol ls;
248
    de_loc  = loc; de_lab = Slab.empty }
249 250

(* helper functions for let-expansion *)
251
let test_var e = match e.de_desc with
252 253 254 255 256
  | DElocal _ | DEglobal_pv _ -> true
  | _ -> false

let mk_var e =
  if test_var e then e else
257 258 259
  { de_desc = DElocal "q";
    de_type = e.de_type;
    de_loc  = e.de_loc;
260
    de_lab  = Slab.empty }
261

262 263 264
let mk_id s loc =
  { id = s; id_loc = loc; id_lab = [] }

265 266
let mk_dexpr desc dvty loc labs =
  { de_desc = desc; de_type = dvty; de_loc = loc; de_lab = labs }
267

268 269
let mk_let ~loc ~uloc e (desc,dvty) =
  if test_var e then desc, dvty else
Andrei Paskevich's avatar
Andrei Paskevich committed
270
  let loc = def_option loc uloc in
271
  let e1 = mk_dexpr desc dvty loc Slab.empty in
272
  DElet (mk_id "q" e.de_loc, false, e, e1), dvty
273

274 275 276
(* patterns *)

let add_var id dity denv =
277 278
  let tvars = add_dity denv.tvars dity in
  let locals = Mstr.add id.id (tvars,([],dity)) denv.locals in
279 280
  { denv with locals = locals; tvars = tvars }

281
let specialize_qualid uc p = match uc_find_ps uc p with
282
  | PV pv -> DEglobal_pv pv, ([],specialize_pvsymbol pv)
283 284 285
  | PS ps -> DEglobal_ps ps, specialize_psymbol  ps
  | PL pl -> DEglobal_pl pl, specialize_plsymbol pl
  | LS ls -> DEglobal_ls ls, specialize_lsymbol ls
286
  | XS xs -> errorm ~loc:(qloc p) "unexpected exception symbol %a" print_xs xs
287

288 289
let find_xsymbol uc p = match uc_find_ps uc p with
  | XS xs -> xs
290
  | _ -> errorm ~loc:(qloc p) "exception symbol expected"
Andrei Paskevich's avatar
Andrei Paskevich committed
291

292
let find_variant_ls uc p = match uc_find_ls uc p with
293 294
  | { ls_args = [u;v]; ls_value = None } as ls when ty_equal u v -> ls
  | ls -> errorm ~loc:(qloc p) "%a is not a binary relation" Pretty.print_ls ls
295

296
let find_global_vs uc p = try match uc_find_ps uc p with
297 298
  | PV pv -> Some pv.pv_vs
  | _ -> None
299
  with _ -> None
300

301 302 303 304 305
let rec dpattern denv ({ pat_loc = loc } as pp) = match pp.pat_desc with
  | Ptree.PPpwild ->
      PPwild, create_type_variable (), denv
  | Ptree.PPpvar id ->
      let dity = create_type_variable () in
306
      PPvar (Denv.create_user_id id), dity, add_var id dity denv
307
  | Ptree.PPpapp (q,ppl) ->
308 309
      let sym, dvty = specialize_qualid denv.uc q in
      dpat_app denv loc (mk_dexpr sym dvty loc Slab.empty) ppl
310
  | Ptree.PPprec fl when is_pure_record denv.uc fl ->
311
      let kn = Theory.get_known (get_theory denv.uc) in
312
      let fl = List.map (find_pure_field denv.uc) fl in
313 314 315
      let cs,pjl,flm = Loc.try2 loc Decl.parse_record kn fl in
      let wild = { pat_desc = Ptree.PPpwild; pat_loc = loc } in
      let get_val pj = Mls.find_def wild pj flm in
316
      dpat_app denv loc (hidden_ls ~loc cs) (List.map get_val pjl)
317
  | Ptree.PPprec fl ->
318
      let fl = List.map (find_prog_field denv.uc) fl in
319 320 321
      let cs,pjl,flm = Loc.try2 loc parse_record denv.uc fl in
      let wild = { pat_desc = Ptree.PPpwild; pat_loc = loc } in
      let get_val pj = Mls.find_def wild pj.pl_ls flm in
322
      dpat_app denv loc (hidden_pl ~loc cs) (List.map get_val pjl)
323 324
  | Ptree.PPptuple ppl ->
      let cs = fs_tuple (List.length ppl) in
325 326 327 328
      dpat_app denv loc (hidden_ls ~loc cs) ppl
  | Ptree.PPpor (lpp1, lpp2) ->
      let pp1, dity1, denv = dpattern denv lpp1 in
      let pp2, dity2, denv = dpattern denv lpp2 in
329
      unify_loc unify lpp2.pat_loc dity1 dity2;
330 331 332
      PPor (pp1, pp2), dity1, denv
  | Ptree.PPpas (pp, id) ->
      let pp, dity, denv = dpattern denv pp in
333
      PPas (pp, Denv.create_user_id id), dity, add_var id dity denv
334

335 336 337 338
and dpat_app denv gloc ({ de_loc = loc } as de) ppl =
  let add_pp lp (ppl, tyl, denv) =
    let pp, ty, denv = dpattern denv lp in
    pp::ppl, (lp.pat_loc,ty)::tyl, denv in
339
  let ppl, tyl, denv = List.fold_right add_pp ppl ([],[],denv) in
340 341 342
  let pp, ls = match de.de_desc with
    | DEglobal_pl pl -> Mlw_expr.PPpapp (pl, ppl), pl.pl_ls
    | DEglobal_ls ls -> Mlw_expr.PPlapp (ls, ppl), ls
343 344
    | DEglobal_pv pv -> errorm ~loc "%a is not a constructor" print_pv pv
    | DEglobal_ps ps -> errorm ~loc "%a is not a constructor" print_ps ps
345 346
    | _ -> assert false
  in
347 348 349 350 351
  let argl, res = de.de_type in
  if List.length argl <> List.length ppl then error ~loc:gloc
    (Term.BadArity (ls, List.length argl, List.length ppl));
  let unify_arg ta (loc,tv) = unify_loc unify loc ta tv in
  List.iter2 unify_arg argl tyl;
352 353
  pp, res, denv

354 355
(* specifications *)

356
let dbinders denv bl =
357
  let hv = Hashtbl.create 3 in
358
  let dbinder (id,gh,pty) (denv,bl,tyl) =
359
    if Hashtbl.mem hv id.id then raise (DuplicateProgVar id.id);
360
    Hashtbl.add hv id.id ();
361
    let dity = match pty with
362
      | Some pty -> dity_of_pty denv pty
363
      | None -> create_type_variable () in
364
    add_var id dity denv, (id,gh,dity)::bl, dity::tyl
365 366
  in
  List.fold_right dbinder bl (denv,[],[])
367 368

let deff_of_peff uc pe =
369 370 371
  { deff_reads  = pe.pe_reads;
    deff_writes = pe.pe_writes;
    deff_raises = List.map (fun (gh,q) -> gh, find_xsymbol uc q) pe.pe_raises; }
372

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
exception DuplicateException of xsymbol

let dxpost uc ql =
  let add_exn m (q,f) =
    let xs = find_xsymbol uc q in
    Mexn.add_new (DuplicateException xs) xs f m in
  List.fold_left add_exn Mexn.empty ql

let dvariant uc var =
  List.map (fun (le,q) -> le, Util.option_map (find_variant_ls uc) q) var

let dspec uc sp = {
  ds_pre     = sp.sp_pre;
  ds_post    = sp.sp_post;
  ds_xpost   = dxpost uc sp.sp_xpost;
  ds_effect  = deff_of_peff uc sp.sp_effect;
  ds_variant = dvariant uc sp.sp_variant;
}
391

392 393 394
let rec dtype_c denv (tyv, sp) =
  let tyv, dvty = dtype_v denv tyv in
  (tyv, dspec denv.uc sp), dvty
395 396 397

and dtype_v denv = function
  | Tpure pty ->
398
      let dity = dity_of_pty denv pty in
399
      DSpecV (false,dity), ([],dity)
400 401
  | Tarrow (bl,tyc) ->
      let denv,bl,tyl = dbinders denv bl in
402 403
      let tyc,(argl,res) = dtype_c denv tyc in
      DSpecA (bl,tyc), (tyl @ argl,res)
404

405
(* expressions *)
406

407
let de_unit ~loc = hidden_ls ~loc (Term.fs_tuple 0)
408

409 410 411 412 413 414 415 416 417 418 419 420 421 422
let de_app _loc e el =
  let argl, res = e.de_type in
  let rec unify_list argl el = match argl, el with
    | arg::argl, e::el when Loc.equal e.de_loc Loc.dummy_position ->
        expected_type e arg; unify_list argl el
    | arg::argl, e::el ->
        let res = unify_list argl el in expected_type e arg; res
    | argl, [] -> argl, res
    | [], _ when fst e.de_type = [] -> errorm ~loc:e.de_loc
        "This expression is not a function and cannot be applied"
    | [], _ -> errorm ~loc:e.de_loc
        "This function is applied to too many arguments"
  in
  DEapply (e, el), unify_list argl el
423

Andrei Paskevich's avatar
Andrei Paskevich committed
424
let rec dexpr denv e =
425
  let loc = e.Ptree.expr_loc in
426
  let labs, uloc, d = extract_labels Slab.empty denv.uloc e in
Andrei Paskevich's avatar
Andrei Paskevich committed
427
  let denv = { denv with uloc = uloc } in
428
  let d, ty = de_desc denv loc d in
Andrei Paskevich's avatar
Andrei Paskevich committed
429
  let loc = def_option loc uloc in
430
  mk_dexpr d ty loc labs
431

432
and de_desc denv loc = function
433 434
  | Ptree.Eident (Qident {id=x}) when Mstr.mem x denv.locals ->
      (* local variable *)
435 436 437
      let tvs, dvty = Mstr.find x denv.locals in
      let dvty = specialize_scheme tvs dvty in
      DElocal x, dvty
438
  | Ptree.Eident p ->
439
      specialize_qualid denv.uc p
440 441
  | Ptree.Eapply (e1, e2) ->
      let e, el = decompose_app [e2] e1 in
Andrei Paskevich's avatar
Andrei Paskevich committed
442
      let el = List.map (dexpr denv) el in
443
      de_app loc (dexpr denv e) el
444
  | Ptree.Elet (id, gh, e1, e2) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
445
      let e1 = dexpr denv e1 in
446
      let dvty = e1.de_type in
447
      let tvars = match e1.de_desc with
Andrei Paskevich's avatar
Andrei Paskevich committed
448
        | DEfun _ -> denv.tvars
449 450
        | _ -> add_dvty denv.tvars dvty in
      let locals = Mstr.add id.id (tvars, dvty) denv.locals in
451
      let denv = { denv with locals = locals; tvars = tvars } in
Andrei Paskevich's avatar
Andrei Paskevich committed
452
      let e2 = dexpr denv e2 in
453
      DElet (id, gh, e1, e2), e2.de_type
454 455
  | Ptree.Eletrec (fdl, e1) ->
      let fdl = dletrec denv fdl in
456
      let add_one denv ({ id = id }, _, dvty, _, _) =
457
        { denv with locals = Mstr.add id (denv.tvars, dvty) denv.locals } in
458
      let denv = List.fold_left add_one denv fdl in
Andrei Paskevich's avatar
Andrei Paskevich committed
459
      let e1 = dexpr denv e1 in
460
      DEletrec (fdl, e1), e1.de_type
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
461
  | Ptree.Efun (bl, tr) ->
462
      let denv, bl, tyl = dbinders denv bl in
463
      let tr, (argl, res) = dtriple denv tr in
464
      DEfun (bl, tr), (tyl @ argl, res)
465
  | Ptree.Ecast (e1, pty) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
466
      let e1 = dexpr denv e1 in
467
      expected_type e1 (dity_of_pty denv pty);
468
      e1.de_desc, e1.de_type
469 470
  | Ptree.Enamed _ ->
      assert false
471
  | Ptree.Esequence (e1, e2) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
472
      let e1 = dexpr denv e1 in
473
      expected_type e1 dity_unit;
Andrei Paskevich's avatar
Andrei Paskevich committed
474
      let e2 = dexpr denv e2 in
475
      DElet (mk_id "_" loc, false, e1, e2), e2.de_type
476
  | Ptree.Eif (e1, e2, e3) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
477
      let e1 = dexpr denv e1 in
478
      expected_type e1 dity_bool;
Andrei Paskevich's avatar
Andrei Paskevich committed
479 480
      let e2 = dexpr denv e2 in
      let e3 = dexpr denv e3 in
481 482 483
      let res = create_type_variable () in
      expected_type e2 res;
      expected_type e3 res;
484
      DEif (e1, e2, e3), e2.de_type
485 486
  | Ptree.Etuple el ->
      let ls = fs_tuple (List.length el) in
Andrei Paskevich's avatar
Andrei Paskevich committed
487
      let el = List.map (dexpr denv) el in
488
      de_app loc (hidden_ls ~loc ls) el
489
  | Ptree.Erecord fl when is_pure_record denv.uc fl ->
490
      let kn = Theory.get_known (get_theory denv.uc) in
491
      let fl = List.map (find_pure_field denv.uc) fl in
492 493
      let cs,pjl,flm = Loc.try2 loc Decl.parse_record kn fl in
      let get_val pj = match Mls.find_opt pj flm with
Andrei Paskevich's avatar
Andrei Paskevich committed
494
        | Some e -> dexpr denv e
495
        | None -> error ~loc (Decl.RecordFieldMissing (cs,pj)) in
496
      de_app loc (hidden_ls ~loc cs) (List.map get_val pjl)
497
  | Ptree.Erecord fl ->
498
      let fl = List.map (find_prog_field denv.uc) fl in
499 500
      let cs,pjl,flm = Loc.try2 loc parse_record denv.uc fl in
      let get_val pj = match Mls.find_opt pj.pl_ls flm with
Andrei Paskevich's avatar
Andrei Paskevich committed
501
        | Some e -> dexpr denv e
502
        | None -> error ~loc (Decl.RecordFieldMissing (cs.pl_ls,pj.pl_ls)) in
503
      de_app loc (hidden_pl ~loc cs) (List.map get_val pjl)
504
  | Ptree.Eupdate (e1, fl) when is_pure_record denv.uc fl ->
Andrei Paskevich's avatar
Andrei Paskevich committed
505
      let e1 = dexpr denv e1 in
506 507
      let e0 = mk_var e1 in
      let kn = Theory.get_known (get_theory denv.uc) in
508
      let fl = List.map (find_pure_field denv.uc) fl in
509 510
      let cs,pjl,flm = Loc.try2 loc Decl.parse_record kn fl in
      let get_val pj = match Mls.find_opt pj flm with
Andrei Paskevich's avatar
Andrei Paskevich committed
511
        | Some e -> dexpr denv e
512
        | None ->
513
            let loc = Loc.dummy_position in
514 515
            let d, dvty = de_app loc (hidden_ls ~loc pj) [e0] in
            mk_dexpr d dvty loc Slab.empty in
516
      let res = de_app loc (hidden_ls ~loc cs) (List.map get_val pjl) in
Andrei Paskevich's avatar
Andrei Paskevich committed
517
      mk_let ~loc ~uloc:denv.uloc e1 res
518
  | Ptree.Eupdate (e1, fl) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
519
      let e1 = dexpr denv e1 in
520
      let e0 = mk_var e1 in
521
      let fl = List.map (find_prog_field denv.uc) fl in
522 523
      let cs,pjl,flm = Loc.try2 loc parse_record denv.uc fl in
      let get_val pj = match Mls.find_opt pj.pl_ls flm with
Andrei Paskevich's avatar
Andrei Paskevich committed
524
        | Some e -> dexpr denv e
525
        | None ->
526
            let loc = Loc.dummy_position in
527 528
            let d, dvty = de_app loc (hidden_pl ~loc pj) [e0] in
            mk_dexpr d dvty loc Slab.empty in
529
      let res = de_app loc (hidden_pl ~loc cs) (List.map get_val pjl) in
Andrei Paskevich's avatar
Andrei Paskevich committed
530
      mk_let ~loc ~uloc:denv.uloc e1 res
Andrei Paskevich's avatar
Andrei Paskevich committed
531
  | Ptree.Eassign (e1, q, e2) ->
532 533
      let fl = { expr_desc = Eident q; expr_loc = loc } in
      let e1 = { expr_desc = Eapply (fl,e1); expr_loc = loc } in
Andrei Paskevich's avatar
Andrei Paskevich committed
534 535
      let e1 = dexpr denv e1 in
      let e2 = dexpr denv e2 in
536 537 538 539
      let res = create_type_variable () in
      expected_type e1 res;
      expected_type_weak e2 res;
      DEassign (e1, e2), ([], dity_unit)
540
  | Ptree.Econstant (ConstInt _ as c) ->
541
      DEconstant c, ([], dity_int)
542
  | Ptree.Econstant (ConstReal _ as c) ->
543
      DEconstant c, ([], dity_real)
544
  | Ptree.Enot e1 ->
Andrei Paskevich's avatar
Andrei Paskevich committed
545
      let e1 = dexpr denv e1 in
546
      expected_type e1 dity_bool;
547
      DEnot e1, ([], dity_bool)
548
  | Ptree.Elazy (op, e1, e2) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
549 550
      let e1 = dexpr denv e1 in
      let e2 = dexpr denv e2 in
551 552
      expected_type e1 dity_bool;
      expected_type e2 dity_bool;
553
      DElazy (op, e1, e2), ([], dity_bool)
554
  | Ptree.Ematch (e1, bl) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
555
      let e1 = dexpr denv e1 in
556
      let ety = create_type_variable () in
557
      let res = create_type_variable () in
558
      expected_type e1 ety;
559 560
      let branch (pp,e) =
        let ppat, dity, denv = dpattern denv pp in
561
        unify_loc unify pp.pat_loc ety dity;
Andrei Paskevich's avatar
Andrei Paskevich committed
562
        let e = dexpr denv e in
563 564
        expected_type e res;
        ppat, e in
565
      DEmatch (e1, List.map branch bl), ([], res)
Andrei Paskevich's avatar
Andrei Paskevich committed
566
  | Ptree.Eraise (q, e1) ->
567
      let xs = find_xsymbol denv.uc q in
568
      let dity = specialize_xsymbol xs in
Andrei Paskevich's avatar
Andrei Paskevich committed
569
      let e1 = match e1 with
Andrei Paskevich's avatar
Andrei Paskevich committed
570
        | Some e1 -> dexpr denv e1
571
        | None when ity_equal xs.xs_ity ity_unit -> de_unit ~loc
Andrei Paskevich's avatar
Andrei Paskevich committed
572 573
        | _ -> errorm ~loc "exception argument expected" in
      expected_type e1 dity;
574
      DEraise (xs, e1), ([], create_type_variable ())
Andrei Paskevich's avatar
Andrei Paskevich committed
575
  | Ptree.Etry (e1, cl) ->
576
      let res = create_type_variable () in
Andrei Paskevich's avatar
Andrei Paskevich committed
577
      let e1 = dexpr denv e1 in
578
      expected_type e1 res;
Andrei Paskevich's avatar
Andrei Paskevich committed
579
      let branch (q, id, e) =
580
        let xs = find_xsymbol denv.uc q in
581
        let dity = specialize_xsymbol xs in
Andrei Paskevich's avatar
Andrei Paskevich committed
582 583
        let id, denv = match id with
          | Some id -> id, add_var id dity denv
584
          | None -> mk_id "void" loc, denv in
585
        let e = dexpr denv e in
586
        expected_type e res;
587
        xs, id, e
Andrei Paskevich's avatar
Andrei Paskevich committed
588 589
      in
      let cl = List.map branch cl in
590
      DEtry (e1, cl), e1.de_type
591
  | Ptree.Eabsurd ->
592
      DEabsurd, ([], create_type_variable ())
593
  | Ptree.Eassert (ak, lexpr) ->
594
      DEassert (ak, lexpr), ([], dity_unit)
Andrei Paskevich's avatar
Andrei Paskevich committed
595 596
  | Ptree.Emark (id, e1) ->
      let e1 = dexpr denv e1 in
597
      DEmark (id, e1), e1.de_type
598
  | Ptree.Eany tyc ->
599 600
      let tyc, dvty = dtype_c denv tyc in
      DEany tyc, dvty
601 602 603
  | Ptree.Eghost e1 ->
      let e1 = dexpr denv e1 in
      DEghost e1, e1.de_type
604
  | Ptree.Eabstract (e1, sp) ->
605
      let e1 = dexpr denv e1 in
606 607
      let sp = dspec denv.uc sp in
      DEabstract (e1, sp), e1.de_type
608 609 610 611 612 613 614 615 616 617 618 619 620 621
  | Ptree.Eloop ({ loop_invariant = inv; loop_variant = var }, e1) ->
      let e1 = dexpr denv e1 in
      let var = dvariant denv.uc var in
      expected_type e1 dity_unit;
      DEloop (var,inv,e1), e1.de_type
  | Ptree.Efor (id, efrom, dir, eto, inv, e1) ->
      let efrom = dexpr denv efrom in
      let eto = dexpr denv eto in
      let denv = add_var id dity_int denv in
      let e1 = dexpr denv e1 in
      expected_type efrom dity_int;
      expected_type eto dity_int;
      expected_type e1 dity_unit;
      DEfor (id,efrom,dir,eto,inv,e1), e1.de_type
622

623
and dletrec denv fdl =
624
  (* add all functions into the environment *)
625
  let add_one denv (_,id,_,bl,_) =
626 627 628 629 630
    let argl = List.map (fun _ -> create_type_variable ()) bl in
    let dvty = argl, create_type_variable () in
    let tvars = add_dvty denv.tvars dvty in
    let locals = Mstr.add id.id (tvars, dvty) denv.locals in
    { denv with locals = locals; tvars = tvars }, dvty in
631
  let denv, dvtyl = Util.map_fold_left add_one denv fdl in
632
  (* then unify the binders *)
633
  let bind_one (_,_,_,bl,_) (argl,res) =
634 635 636
    let denv,bl,tyl = dbinders denv bl in
    List.iter2 unify argl tyl;
    denv,bl,tyl,res in
637
  let denvl = List.map2 bind_one fdl dvtyl in
638
  (* then type-check the bodies *)
639 640
  let type_one (loc,id,gh,_,tr) (denv,bl,tyl,tyv) =
    let tr, (argl, res) = dtriple denv tr in
641 642 643
    if argl <> [] then errorm ~loc
      "The body of a recursive function must be a first-order value";
    unify_loc unify loc tyv res;
644
    id, gh, (tyl, tyv), bl, tr in
645
  List.map2 type_one fdl denvl
Andrei Paskevich's avatar
Andrei Paskevich committed
646

647
and dtriple denv (e, sp) =
Andrei Paskevich's avatar
Andrei Paskevich committed
648
  let e = dexpr denv e in
649 650
  let sp = dspec denv.uc sp in
  (e, sp), e.de_type
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
651

652
(** stage 2 *)
653

Andrei Paskevich's avatar
Andrei Paskevich committed
654 655
type lenv = {
  mod_uc   : module_uc;
656 657
  th_at    : Theory.theory_uc;
  th_old   : Theory.theory_uc;
658
  let_vars : let_sym Mstr.t;
Andrei Paskevich's avatar
Andrei Paskevich committed
659 660
  log_vars : vsymbol Mstr.t;
  log_denv : Typing.denv;
661 662
}

Andrei Paskevich's avatar
Andrei Paskevich committed
663
let create_lenv uc = {
664 665 666
  mod_uc   = uc;
  th_at    = Theory.use_export (get_theory uc) Mlw_wp.th_mark_at;
  th_old   = Theory.use_export (get_theory uc) Mlw_wp.th_mark_old;
667 668
  let_vars = Mstr.empty;
  log_vars = Mstr.empty;
669
  log_denv = Typing.denv_empty_with_globals (find_global_vs uc);
670 671
}

672 673
(* invariant handling *)

Andrei Paskevich's avatar
Andrei Paskevich committed
674
let env_invariant lenv eff pvs =
675 676
  let kn = get_known lenv.mod_uc in
  let lkn = Theory.get_known (get_theory lenv.mod_uc) in
677
  let regs = Sreg.union eff.eff_writes eff.eff_ghostw in
Andrei Paskevich's avatar
Andrei Paskevich committed
678 679
  let add_pv pv (pinv,qinv) =
    let ity = pv.pv_vtv.vtv_ity in
680
    let written r = reg_occurs r ity.ity_vars in
Andrei Paskevich's avatar
Andrei Paskevich committed
681
    let inv = Mlw_wp.full_invariant lkn kn pv.pv_vs ity in
682 683 684 685
    let qinv = (* we reprove invariants for modified non-reset variables *)
      if Sreg.exists written regs && not (eff_stale_region eff ity.ity_vars)
      then t_and_simp qinv inv else qinv in
    t_and_simp pinv inv, qinv
686
  in
Andrei Paskevich's avatar
Andrei Paskevich committed
687
  Spv.fold add_pv pvs (t_true,t_true)
688

689 690 691 692 693 694 695 696 697 698 699 700 701 702
let rec check_reset rvs t = match t.t_node with
  | Tvar vs when Svs.mem vs rvs ->
      errorm "The variable %s is reset and can only be used \
        under `old' in the postcondition" vs.vs_name.id_string
  | Tapp (ls,_) when ls_equal ls fs_at -> false
  | Tlet _ | Tcase _ | Teps _ | Tquant _ ->
      let rvs = Mvs.set_inter rvs t.t_vars in
      if Mvs.is_empty rvs then false else
      t_any (check_reset rvs) t
  | _ ->
      t_any (check_reset rvs) t

let post_invariant lenv rvs inv ity q =
  ignore (check_reset rvs q);
703 704 705 706 707 708 709
  let vs, q = open_post q in
  let kn = get_known lenv.mod_uc in
  let lkn = Theory.get_known (get_theory lenv.mod_uc) in
  let res_inv = Mlw_wp.full_invariant lkn kn vs ity in
  let q = t_and_asym_simp q (t_and_simp res_inv inv) in
  Mlw_ty.create_post vs q

Andrei Paskevich's avatar
Andrei Paskevich committed
710 711 712 713
let ity_or_unit = function
  | VTvalue v -> v.vtv_ity
  | VTarrow _ -> ity_unit

714 715 716 717 718 719 720
let reset_vars eff pvs =
  let add pv s =
    if eff_stale_region eff pv.pv_vtv.vtv_ity.ity_vars
    then Svs.add pv.pv_vs s else s in
  if Mreg.is_empty eff.eff_resets then Svs.empty else
  Spv.fold add pvs Svs.empty

721 722 723 724 725 726 727 728 729 730 731
(* add dummy postconditions for uncovered exceptions *)
let complete_xpost eff xq =
  let xe = Sexn.union eff.eff_raises eff.eff_ghostx in
  let check xs _ = Loc.errorm
    "this expression does not raise exception %a" print_xs xs in
  Mexn.iter check (Mexn.set_diff xq xe);
  let dummy { xs_ity = ity } () =
    let v = create_vsymbol (id_fresh "dummy") (ty_of_ity ity) in
    Mlw_ty.create_post v t_true in
  Mexn.set_union xq (Mexn.mapi dummy (Mexn.set_diff xe xq))

Andrei Paskevich's avatar
Andrei Paskevich committed
732 733 734
let spec_invariant lenv pvs vty spec =
  let ity = ity_or_unit vty in
  let pvs = spec_pvset pvs spec in
735
  let rvs = reset_vars spec.c_effect pvs in
736
  let xpost = complete_xpost spec.c_effect spec.c_xpost in
Andrei Paskevich's avatar
Andrei Paskevich committed
737
  let pinv,qinv = env_invariant lenv spec.c_effect pvs in
738
  let post_inv = post_invariant lenv rvs qinv in
739
  let xpost_inv xs q = post_inv xs.xs_ity q in
740
  { spec with c_pre   = t_and_simp spec.c_pre pinv;
741
              c_post  = post_inv ity spec.c_post;
742
              c_xpost = Mexn.mapi xpost_inv xpost }
743

744 745 746 747 748 749
let abstr_invariant lenv e spec0 =
  let pvs = e_pvset Spv.empty e in
  let spec = { spec0 with c_effect = e.e_effect } in
  let spec = spec_invariant lenv pvs e.e_vty spec in
  (* we do not require invariants on free variables *)
  { spec with c_pre = spec0.c_pre }
750

751
let lambda_invariant lenv pvs eff lam =
Andrei Paskevich's avatar
Andrei Paskevich committed
752
  let pvs = List.fold_right Spv.add lam.l_args pvs in
753 754 755
  let spec = { lam.l_spec with c_effect = eff } in
  let spec = spec_invariant lenv pvs lam.l_expr.e_vty spec in
  { lam with l_spec = spec }
756

757
let rec dty_of_ty ty = match ty.ty_node with
758 759
  | Ty.Tyapp (ts, tyl) -> Denv.tyapp ts (List.map dty_of_ty tyl)
  | Ty.Tyvar v -> Denv.tyuvar v
760

761 762 763 764
let create_post lenv x ty f =
  let res = create_vsymbol (id_fresh x) ty in
  let log_vars = Mstr.add x res lenv.log_vars in
  let log_denv = Typing.add_var x (dty_of_ty ty) lenv.log_denv in
765 766
  let f = Typing.type_fmla lenv.th_old log_denv log_vars f in
  let f = remove_old f in
767
  count_term_tuples f;
Andrei Paskevich's avatar
Andrei Paskevich committed
768
  check_at f;
769
  create_post res f
770

771 772 773
let create_xpost lenv x xs f = create_post lenv x (ty_of_ity xs.xs_ity) f
let create_post lenv x vty f = create_post lenv x (ty_of_vty vty) f

774 775
let create_xpost lenv x xq = Mexn.mapi (create_xpost lenv x) xq

776
let create_pre lenv f =
777
  let f = Typing.type_fmla lenv.th_at lenv.log_denv lenv.log_vars f in
778
  count_term_tuples f;
Andrei Paskevich's avatar
Andrei Paskevich committed
779
  check_at f;
780
  f
781

782
let create_variant lenv (t,r) =
783
  let t = Typing.type_term lenv.th_at lenv.log_denv lenv.log_vars t in
784
  count_term_tuples t;
Andrei Paskevich's avatar
Andrei Paskevich committed
785
  check_at t;
786
  t, r
Andrei Paskevich's avatar
Andrei Paskevich committed
787

Andrei Paskevich's avatar
Andrei Paskevich committed
788
let add_local x lv lenv = match lv with
789
  | LetA _ ->
Andrei Paskevich's avatar
Andrei Paskevich committed
790
      { lenv with let_vars = Mstr.add x lv lenv.let_vars }
791 792
  | LetV pv ->
      let dty = dty_of_ty pv.pv_vs.vs_ty in
793
      { lenv with
Andrei Paskevich's avatar
Andrei Paskevich committed
794 795 796
        let_vars = Mstr.add x lv lenv.let_vars;
        log_vars = Mstr.add x pv.pv_vs lenv.log_vars;
        log_denv = Typing.add_var x dty lenv.log_denv }
797

798 799
let binders bl =
  let binder (id, ghost, dity) =