typing.ml 54.6 KB
Newer Older
Andrei Paskevich's avatar
Andrei Paskevich committed
1 2 3
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
Guillaume Melquiond's avatar
Guillaume Melquiond committed
4
(*  Copyright 2010-2018   --   Inria - CNRS - Paris-Sud University  *)
Andrei Paskevich's avatar
Andrei Paskevich committed
5 6 7 8
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
9
(*                                                                  *)
Andrei Paskevich's avatar
Andrei Paskevich committed
10
(********************************************************************)
11

12
open Wstdlib
13
open Ident
14
open Ptree
15
open Ty
16
open Term
Andrei Paskevich's avatar
Andrei Paskevich committed
17
open Decl
18
open Theory
19
open Dterm
Andrei Paskevich's avatar
Andrei Paskevich committed
20
open Ity
21
open Expr
22 23
open Pdecl
open Pmodule
Andrei Paskevich's avatar
Andrei Paskevich committed
24

25
(** debug flags *)
26

27
let debug_parse_only = Debug.register_flag "parse_only"
Andrei Paskevich's avatar
Andrei Paskevich committed
28
  ~desc:"Stop@ after@ parsing."
29

30
let debug_type_only  = Debug.register_flag "type_only"
Andrei Paskevich's avatar
Andrei Paskevich committed
31
  ~desc:"Stop@ after@ type-checking."
32

33
(** symbol lookup *)
34 35

let rec qloc = function
36 37 38
  | Qdot (p, id) -> Loc.join (qloc p) id.id_loc
  | Qident id    -> id.id_loc

39 40 41
let qloc_last = function
  | Qdot (_, id) | Qident id -> id.id_loc

42
let rec print_qualid fmt = function
43 44
  | Qdot (p, id) -> Format.fprintf fmt "%a.%s" print_qualid p id.id_str
  | Qident id    -> Format.fprintf fmt "%s" id.id_str
45

46 47
let string_list_of_qualid q =
  let rec sloq acc = function
48 49
    | Qdot (p, id) -> sloq (id.id_str :: acc) p
    | Qident id -> id.id_str :: acc in
50
  sloq [] q
51

52
exception UnboundSymbol of qualid
53

54
let find_qualid get_id find ns q =
55 56 57
  let sl = string_list_of_qualid q in
  let r = try find ns sl with Not_found ->
    Loc.error ~loc:(qloc q) (UnboundSymbol q) in
58
  if Debug.test_flag Glob.flag then Glob.use ~kind:"" (qloc_last q) (get_id r);
59
  r
60

61 62 63
let find_prop_ns     ns q = find_qualid (fun pr -> pr.pr_name) ns_find_pr ns q
let find_tysymbol_ns ns q = find_qualid (fun ts -> ts.ts_name) ns_find_ts ns q
let find_lsymbol_ns  ns q = find_qualid (fun ls -> ls.ls_name) ns_find_ls ns q
64

65 66
let find_fsymbol_ns ns q =
  let ls = find_lsymbol_ns ns q in
67 68
  if ls.ls_value <> None then ls else
    Loc.error ~loc:(qloc q) (FunctionSymbolExpected ls)
69

70 71
let find_psymbol_ns ns q =
  let ls = find_lsymbol_ns ns q in
72 73
  if ls.ls_value = None then ls else
    Loc.error ~loc:(qloc q) (PredicateSymbolExpected ls)
74

75 76 77 78
let find_tysymbol tuc q = find_tysymbol_ns (Theory.get_namespace tuc) q
let find_lsymbol  tuc q = find_lsymbol_ns  (Theory.get_namespace tuc) q
let find_fsymbol  tuc q = find_fsymbol_ns  (Theory.get_namespace tuc) q
let find_psymbol  tuc q = find_psymbol_ns  (Theory.get_namespace tuc) q
79 80 81 82
let find_prop     tuc q = find_prop_ns     (Theory.get_namespace tuc) q

let find_prop_of_kind k tuc q =
  let pr = find_prop tuc q in
Andrei Paskevich's avatar
Andrei Paskevich committed
83
  match (Mid.find pr.pr_name tuc.uc_known).d_node with
84
  | Dind _ when k = Paxiom -> pr
85 86 87
  | Dprop (l,_,_) when l = k -> pr
  | _ -> Loc.errorm ~loc:(qloc q) "proposition %a is not %s"
      print_qualid q (match k with
88
        | Plemma -> "a lemma" | Paxiom -> "an axiom" | Pgoal -> "a goal")
89

Andrei Paskevich's avatar
Andrei Paskevich committed
90 91 92
let find_itysymbol_ns ns q =
  find_qualid (fun s -> s.its_ts.ts_name) Pmodule.ns_find_its ns q

93 94 95
let find_xsymbol_ns ns q =
  find_qualid (fun s -> s.xs_name) Pmodule.ns_find_xs ns q

96 97 98
let find_prog_symbol_ns ns p =
  let get_id_ps = function
    | PV pv -> pv.pv_vs.vs_name
99 100 101 102
    | RS rs -> rs.rs_name
      (* FIXME: this is incorrect, but we cannot
        know the correct symbol at this stage *)
    | OO ss -> (Srs.choose ss).rs_name in
103 104 105
  find_qualid get_id_ps ns_find_prog_symbol ns p


106 107
(** Parsing types *)

108
let ty_of_pty ns pty =
109
  let rec get_ty = function
110
    | PTtyvar {id_str = x} ->
111
        ty_var (tv_of_string x)
112
    | PTtyapp (q, tyl) ->
113
        let ts = find_tysymbol_ns ns q in
114
        let tyl = List.map get_ty tyl in
115
        Loc.try2 ~loc:(qloc q) ty_app ts tyl
116
    | PTtuple tyl ->
117 118
        let s = its_tuple (List.length tyl) in
        ty_app s.its_ts (List.map get_ty tyl)
119
    | PTarrow (ty1, ty2) ->
120
        ty_func (get_ty ty1) (get_ty ty2)
Andrei Paskevich's avatar
Andrei Paskevich committed
121
    | PTpure ty | PTparen ty ->
122 123 124 125
        get_ty ty
  in
  get_ty pty

126 127
let dty_of_pty ns pty =
  Dterm.dty_of_ty (ty_of_pty ns pty)
128

129 130
let dty_of_opt ns = function
  | Some pty -> dty_of_pty ns pty
131 132
  | None -> Dterm.dty_fresh ()

133
(** typing using destructive type variables
134

135 136 137 138 139 140
    parsed trees        intermediate trees       typed trees
      (Ptree)                (Dterm)               (Term)
   -----------------------------------------------------------
     ppure_type  ---dty--->   dty       ---ty--->    ty
      lexpr      --dterm-->   dterm     --term-->    term
*)
141

142 143
(** Typing patterns, terms, and formulas *)

144
let create_user_id {id_str = n; id_lab = label; id_loc = loc} =
145 146 147 148
  let get_labels (label, loc) = function
    | Lstr lab -> Slab.add lab label, loc | Lpos loc -> label, loc in
  let label,loc = List.fold_left get_labels (Slab.empty,loc) label in
  id_user ~label n loc
149

150 151 152
let parse_record ~loc ns km get_val fl =
  let fl = List.map (fun (q,e) -> find_lsymbol_ns ns q, e) fl in
  let cs,pjl,flm = Loc.try2 ~loc parse_record km fl in
153 154 155
  let get_val pj = get_val cs pj (Mls.find_opt pj flm) in
  cs, List.map get_val pjl

156
let rec dpattern ns km { pat_desc = desc; pat_loc = loc } =
157
  Dterm.dpattern ~loc (match desc with
158
    | Ptree.Pwild -> DPwild
159 160
    | Ptree.Pvar (x, false) -> DPvar (create_user_id x)
    | Ptree.Papp (q, pl) ->
161 162
        let pl = List.map (dpattern ns km) pl in
        DPapp (find_lsymbol_ns ns q, pl)
163
    | Ptree.Ptuple pl ->
164
        let pl = List.map (dpattern ns km) pl in
165
        DPapp (fs_tuple (List.length pl), pl)
166
    | Ptree.Prec fl ->
167
        let get_val _ _ = function
168
          | Some p -> dpattern ns km p
169
          | None -> Dterm.dpattern DPwild in
170
        let cs,fl = parse_record ~loc ns km get_val fl in
171
        DPapp (cs,fl)
172
    | Ptree.Pas (p, x, false) -> DPas (dpattern ns km p, create_user_id x)
173
    | Ptree.Por (p, q) -> DPor (dpattern ns km p, dpattern ns km q)
174
    | Ptree.Pcast (p, ty) -> DPcast (dpattern ns km p, dty_of_pty ns ty)
175 176
    | Ptree.Pvar (_, true) | Ptree.Pas (_, _, true) -> Loc.errorm ~loc
        "ghost variables are only allowed in programs")
177

178
let quant_var ns (loc, id, gh, ty) =
179
  if gh then Loc.errorm ~loc "ghost variables are only allowed in programs";
180
  Opt.map create_user_id id, dty_of_opt ns ty, Some loc
181

182 183 184 185 186 187
let loc_cutoff loc13 loc23 loc2 =
  let f,l,b,e = Loc.get loc13 in
  let _,_,_,w = Loc.get loc23 in
  let _,_,_,m = Loc.get loc2 in
  Loc.user_position f l b (e - (w - m))

188 189 190 191 192
let is_reusable dt = match dt.dt_node with
  | DTvar _ | DTgvar _ | DTconst _ | DTtrue | DTfalse -> true
  | DTapp (_,[]) -> true
  | _ -> false

193
let mk_var crcmap n dt =
194 195 196
  let dty = match dt.dt_dty with
    | None -> dty_of_ty ty_bool
    | Some dty -> dty in
197
  Dterm.dterm crcmap ?loc:dt.dt_loc (DTvar (n, dty))
198

199 200
let mk_let crcmap ~loc n dt node =
  DTlet (dt, id_user n loc, Dterm.dterm crcmap ~loc node)
201

202 203
let mk_closure crcmap loc ls =
  let mk dt = Dterm.dterm crcmap ~loc dt in
204
  let mk_v i _ =
205 206
    Some (id_user ("y" ^ string_of_int i) loc), dty_fresh (), None in
  let mk_t (id, dty, _) = mk (DTvar ((Opt.get id).pre_name, dty)) in
207
  let vl = Lists.mapi mk_v ls.ls_args in
Andrei Paskevich's avatar
Andrei Paskevich committed
208
  DTquant (DTlambda, vl, [], mk (DTapp (ls, List.map mk_t vl)))
209

210 211 212
(* track the use of labels *)
let at_uses = Hstr.create 5

213
let rec dterm ns km crcmap gvars at denv {term_desc = desc; term_loc = loc} =
214 215
  let func_app e el =
    List.fold_left (fun e1 (loc, e2) ->
216
      DTfapp (Dterm.dterm crcmap ~loc e1, e2)) e el
217
  in
218 219 220
  let rec apply_ls loc ls al l el = match l, el with
    | (_::l), (e::el) -> apply_ls loc ls (e::al) l el
    | [], _ -> func_app (DTapp (ls, List.rev_map snd al)) el
221
    | _, [] -> func_app (mk_closure crcmap loc ls) (List.rev_append al el)
222
  in
223
  let qualid_app q el = match gvars at q with
224 225 226 227 228 229 230 231 232
    | Some v ->
        begin match at with
        | Some l -> (* check for impact *)
            let u = Opt.get (gvars None q) in
            if not (pv_equal v u) then
              Hstr.replace at_uses l true
        | None -> ()
        end;
        func_app (DTgvar v.pv_vs) el
233
    | None ->
234
        let ls = find_lsymbol_ns ns q in
235
        apply_ls (qloc q) ls [] ls.ls_args el
236
  in
237
  let qualid_app q el = match q with
238
    | Qident {id_str = n} ->
239
        (match denv_get_opt denv n with
240 241 242 243
        | Some d -> func_app d el
        | None -> qualid_app q el)
    | _ -> qualid_app q el
  in
244
  let rec unfold_app e1 e2 el = match e1.term_desc with
245
    | Ptree.Tapply (e11,e12) ->
246
        let e12 = dterm ns km crcmap gvars at denv e12 in
247
        unfold_app e11 e12 ((e1.term_loc, e2)::el)
248
    | Ptree.Tident q ->
249
        qualid_app q ((e1.term_loc, e2)::el)
250
    | _ ->
251
        func_app (DTfapp (dterm ns km crcmap gvars at denv e1, e2)) el
252
  in
253
  Dterm.dterm crcmap ~loc (match desc with
254
  | Ptree.Tident q ->
255
      qualid_app q []
256
  | Ptree.Tidapp (q, tl) ->
257
      let tl = List.map (dterm ns km crcmap gvars at denv) tl in
258
      DTapp (find_lsymbol_ns ns q, tl)
259
  | Ptree.Tapply (e1, e2) ->
260
      unfold_app e1 (dterm ns km crcmap gvars at denv e2) []
261
  | Ptree.Ttuple tl ->
262
      let tl = List.map (dterm ns km crcmap gvars at denv) tl in
263
      DTapp (fs_tuple (List.length tl), tl)
264 265 266 267 268
  | Ptree.Tinfix (e1, op1, e23)
  | Ptree.Tinnfix (e1, op1, e23) ->
      let apply loc de1 op de2 =
        if op.id_str = "infix <>" then
          let op = { op with id_str = "infix =" } in
269 270
          let ls = find_lsymbol_ns ns (Qident op) in
          DTnot (Dterm.dterm crcmap ~loc (DTapp (ls, [de1;de2])))
271
        else
272
          DTapp (find_lsymbol_ns ns (Qident op), [de1;de2]) in
273 274
      let rec chain loc de1 op1 = function
        | { term_desc = Ptree.Tinfix (e2, op2, e3); term_loc = loc23 } ->
275
            let de2 = dterm ns km crcmap gvars at denv e2 in
276
            let loc12 = loc_cutoff loc loc23 e2.term_loc in
277 278
            let de12 = Dterm.dterm crcmap ~loc:loc12 (apply loc12 de1 op1 de2) in
            let de23 = Dterm.dterm crcmap ~loc:loc23 (chain loc23 de2 op2 e3) in
279
            DTbinop (DTand, de12, de23)
280
        | e23 ->
281 282
            apply loc de1 op1 (dterm ns km crcmap gvars at denv e23) in
      chain loc (dterm ns km crcmap gvars at denv e1) op1 e23
Clément Fumex's avatar
Clément Fumex committed
283
  | Ptree.Tconst (Number.ConstInt _ as c) ->
284
      DTconst (c, dty_int)
Clément Fumex's avatar
Clément Fumex committed
285
  | Ptree.Tconst (Number.ConstReal _ as c) ->
286
      DTconst (c, dty_real)
287
  | Ptree.Tlet (x, e1, e2) ->
288
      let id = create_user_id x in
289
      let e1 = dterm ns km crcmap gvars at denv e1 in
290
      let denv = denv_add_let denv e1 id in
291
      let e2 = dterm ns km crcmap gvars at denv e2 in
292
      DTlet (e1, id, e2)
293
  | Ptree.Tcase (e1, bl) ->
294
      let e1 = dterm ns km crcmap gvars at denv e1 in
295
      let branch (p, e) =
296
        let p = dpattern ns km p in
297
        let denv = denv_add_term_pat denv p e1 in
298
        p, dterm ns km crcmap gvars at denv e in
299
      DTcase (e1, List.map branch bl)
300
  | Ptree.Tif (e1, e2, e3) ->
301 302 303
      let e1 = dterm ns km crcmap gvars at denv e1 in
      let e2 = dterm ns km crcmap gvars at denv e2 in
      let e3 = dterm ns km crcmap gvars at denv e3 in
304
      DTif (e1, e2, e3)
305
  | Ptree.Ttrue ->
306
      DTtrue
307
  | Ptree.Tfalse ->
308
      DTfalse
Andrei Paskevich's avatar
Andrei Paskevich committed
309
  | Ptree.Tnot e1 ->
310
      DTnot (dterm ns km crcmap gvars at denv e1)
Andrei Paskevich's avatar
Andrei Paskevich committed
311 312 313 314
  | Ptree.Tbinop (e1, Dterm.DTiff, e23)
  | Ptree.Tbinnop (e1, Dterm.DTiff, e23) ->
      let rec chain loc de1 = function
        | { term_desc = Ptree.Tbinop (e2, DTiff, e3); term_loc = loc23 } ->
315
            let de2 = dterm ns km crcmap gvars at denv e2 in
Andrei Paskevich's avatar
Andrei Paskevich committed
316
            let loc12 = loc_cutoff loc loc23 e2.term_loc in
317 318
            let de12 = Dterm.dterm crcmap ~loc:loc12 (DTbinop (DTiff, de1, de2)) in
            let de23 = Dterm.dterm crcmap ~loc:loc23 (chain loc23 de2 e3) in
Andrei Paskevich's avatar
Andrei Paskevich committed
319 320 321 322 323
            DTbinop (DTand, de12, de23)
        | { term_desc = Ptree.Tbinop (_, DTimplies, _); term_loc = loc23 } ->
            Loc.errorm ~loc:loc23 "An unparenthesized implication cannot be \
              placed at the right hand side of an equivalence"
        | e23 ->
324 325
            DTbinop (DTiff, de1, (dterm ns km crcmap gvars at denv e23)) in
      chain loc (dterm ns km crcmap gvars at denv e1) e23
Andrei Paskevich's avatar
Andrei Paskevich committed
326 327
  | Ptree.Tbinop (e1, op, e2)
  | Ptree.Tbinnop (e1, op, e2) ->
328 329
      let e1 = dterm ns km crcmap gvars at denv e1 in
      let e2 = dterm ns km crcmap gvars at denv e2 in
330
      DTbinop (op, e1, e2)
331
  | Ptree.Tquant (q, uqu, trl, e1) ->
332
      let qvl = List.map (quant_var ns) uqu in
333
      let denv = denv_add_quant denv qvl in
334
      let dterm e = dterm ns km crcmap gvars at denv e in
335 336
      let trl = List.map (List.map dterm) trl in
      let e1 = dterm e1 in
Andrei Paskevich's avatar
Andrei Paskevich committed
337
      DTquant (q, qvl, trl, e1)
338
  | Ptree.Trecord fl ->
339
      let get_val _cs pj = function
340
        | Some e -> dterm ns km crcmap gvars at denv e
341
        | None -> Loc.error ~loc (RecordFieldMissing pj) in
342
      let cs, fl = parse_record ~loc ns km get_val fl in
343
      DTapp (cs, fl)
344
  | Ptree.Tupdate (e1, fl) ->
345
      let e1 = dterm ns km crcmap gvars at denv e1 in
346
      let re = is_reusable e1 in
347
      let v = if re then e1 else mk_var crcmap "q " e1 in
348
      let get_val _ pj = function
349 350
        | Some e -> dterm ns km crcmap gvars at denv e
        | None -> Dterm.dterm crcmap ~loc (DTapp (pj,[v])) in
351
      let cs, fl = parse_record ~loc ns km get_val fl in
352
      let d = DTapp (cs, fl) in
353
      if re then d else mk_let crcmap ~loc "q " e1 d
354
  | Ptree.Tat (e1, ({id_str = l; id_loc = loc} as id)) ->
355
      Hstr.add at_uses l false;
356 357 358
      let id = { id with id_str = "" } in
      (* check if the label has actually been defined *)
      ignore (Loc.try2 ~loc gvars (Some l) (Qident id));
359
      let e1 = dterm ns km crcmap gvars (Some l) denv e1 in
360 361
      if not (Hstr.find at_uses l) then Loc.errorm ~loc
        "this `at'/`old' operator is never used";
362 363
      Hstr.remove at_uses l;
      DTlabel (e1, Slab.empty)
Andrei Paskevich's avatar
M.()  
Andrei Paskevich committed
364
  | Ptree.Tscope (q, e1) ->
365 366
      let ns = import_namespace ns (string_list_of_qualid q) in
      DTlabel (dterm ns km crcmap gvars at denv e1, Slab.empty)
367
  | Ptree.Tnamed (Lpos uloc, e1) ->
368
      DTuloc (dterm ns km crcmap gvars at denv e1, uloc)
369
  | Ptree.Tnamed (Lstr lab, e1) ->
370
      DTlabel (dterm ns km crcmap gvars at denv e1, Slab.singleton lab)
371
  | Ptree.Tcast ({term_desc = Ptree.Tconst c}, pty) ->
372
      DTconst (c, dty_of_pty ns pty)
373
  | Ptree.Tcast (e1, pty) ->
374 375
      let d1 = dterm ns km crcmap gvars at denv e1 in
      DTcast (d1, dty_of_pty ns pty))
Andrei Paskevich's avatar
Andrei Paskevich committed
376

377

378 379 380 381
let no_gvars at q = match at with
  | Some _ -> Loc.errorm ~loc:(qloc q)
      "`at' and `old' can only be used in program annotations"
  | None -> None
382

383 384
let type_term_in_namespace ns km crcmap t =
  let t = dterm ns km crcmap no_gvars None Dterm.denv_empty t in
385 386
  Dterm.term ~strict:true ~keep_loc:true t

387 388
let type_fmla_in_namespace ns km crcmap f =
  let f = dterm ns km crcmap no_gvars None Dterm.denv_empty f in
389
  Dterm.fmla ~strict:true ~keep_loc:true f
Andrei Paskevich's avatar
Andrei Paskevich committed
390

391

392
(** typing program expressions *)
Andrei Paskevich's avatar
Andrei Paskevich committed
393

394 395
open Dexpr

396
let ty_of_pty tuc = ty_of_pty (get_namespace tuc)
397

398
let get_namespace muc = List.hd muc.Pmodule.muc_import
399

400

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
let dterm muc =
  let uc = muc.muc_theory in
  dterm (Theory.get_namespace uc) uc.uc_known uc.uc_crcmap

let find_xsymbol     muc q = find_xsymbol_ns     (get_namespace muc) q
let find_itysymbol   muc q = find_itysymbol_ns   (get_namespace muc) q
let find_prog_symbol muc q = find_prog_symbol_ns (get_namespace muc) q

let find_special muc test nm q =
  match find_prog_symbol muc q with
  | RS s when test s -> s
  | OO ss ->
      begin match Srs.elements (Srs.filter test ss) with
      | [s] -> s
      | _::_ -> Loc.errorm ~loc:(qloc q)
                          "Ambiguous %s notation: %a" nm print_qualid q
      | [] -> Loc.errorm ~loc:(qloc q) "Not a %s: %a" nm print_qualid q
      end
  | _ ->      Loc.errorm ~loc:(qloc q) "Not a %s: %a" nm print_qualid q

let ity_of_pty muc pty =
  let rec get_ity = function
    | PTtyvar {id_str = x} ->
        ity_var (tv_of_string x)
    | PTtyapp (q, tyl) ->
        let s = find_itysymbol_ns (get_namespace muc) q in
        let tyl = List.map get_ity tyl in
        Loc.try3 ~loc:(qloc q) ity_app s tyl []
    | PTtuple tyl ->
        ity_tuple (List.map get_ity tyl)
    | PTarrow (ty1, ty2) ->
        ity_func (get_ity ty1) (get_ity ty2)
    | PTpure ty ->
        ity_purify (get_ity ty)
    | PTparen ty ->
        get_ity ty
  in
  get_ity pty


let dity_of_pty muc pty =
  Dexpr.dity_of_ity (ity_of_pty muc pty)

let dity_of_opt muc = function
  | Some pty -> dity_of_pty muc pty
  | None -> Dexpr.dity_fresh ()

448 449 450
(* records *)

let find_record_field muc q =
451 452
  let test rs = rs.rs_field <> None in
  find_special muc test "record field" q
453 454 455 456 457 458 459 460 461 462 463 464

let find_record_field2 muc (q,e) = find_record_field muc q, e

let parse_record muc fll =
  (* we assume that every rsymbol in fll was resolved
     using find_record_field, so they are all fields *)
  let ls_of_rs rs = match rs.rs_logic with
    | RLls ls -> ls | _ -> assert false in
  let rs = match fll with
    | (rs, _)::_ -> rs
    | [] -> raise EmptyRecord in
  let its = match rs.rs_cty.cty_args with
465
    | [{pv_ity = {ity_node = (Ityreg {reg_its = s} | Ityapp (s,_,_))}}] -> s
466 467 468 469 470 471 472 473 474 475
    | _ -> raise (BadRecordField (ls_of_rs rs)) in
  let itd = find_its_defn muc.muc_known its in
  let check v s = match s.rs_field with
    | Some u -> pv_equal v u
    | _ -> false in
  let cs = match itd.itd_constructors with
    | [cs] when Lists.equal check cs.rs_cty.cty_args itd.itd_fields -> cs
    | _ -> raise (BadRecordField (ls_of_rs rs)) in
  let pjs = Srs.of_list itd.itd_fields in
  let flm = List.fold_left (fun m (pj,v) -> if Srs.mem pj pjs then
476
    Mrs.add_new (DuplicateRecordField (ls_of_rs pj)) pj v m
477 478 479 480 481 482 483 484 485 486 487
    else raise (BadRecordField (ls_of_rs pj))) Mrs.empty fll in
  cs, itd.itd_fields, flm

let parse_record ~loc muc get_val fl =
  let fl = List.map (find_record_field2 muc) fl in
  let cs,pjl,flm = Loc.try2 ~loc parse_record muc fl in
  let get_val pj = get_val cs pj (Mrs.find_opt pj flm) in
  cs, List.map get_val pjl

(* patterns *)

488 489 490 491 492 493
let find_constructor muc q =
  let test rs = match rs.rs_logic with
    | RLls {ls_constr = c} -> c > 0
    | _ -> false in
  find_special muc test "constructor" q

494 495 496
let rec dpattern muc { pat_desc = desc; pat_loc = loc } =
  Dexpr.dpattern ~loc (match desc with
    | Ptree.Pwild -> DPwild
497 498
    | Ptree.Pvar (x, gh) -> DPvar (create_user_id x, gh)
    | Ptree.Papp (q, pl) ->
499
        DPapp (find_constructor muc q, List.map (dpattern muc) pl)
500 501 502 503 504 505 506 507
    | Ptree.Prec fl ->
        let get_val _ _ = function
          | Some p -> dpattern muc p
          | None -> Dexpr.dpattern DPwild in
        let cs,fl = parse_record ~loc muc get_val fl in
        DPapp (cs,fl)
    | Ptree.Ptuple pl ->
        DPapp (rs_tuple (List.length pl), List.map (dpattern muc) pl)
508
    | Ptree.Pcast (p, pty) -> DPcast (dpattern muc p, dity_of_pty muc pty)
509
    | Ptree.Pas (p, x, gh) -> DPas (dpattern muc p, create_user_id x, gh)
510 511
    | Ptree.Por (p, q) -> DPor (dpattern muc p, dpattern muc q))

512

513 514 515 516 517 518 519 520 521 522
(* specifications *)

let find_global_pv muc q = try match find_prog_symbol muc q with
  | PV v -> Some v | _ -> None with _ -> None

let find_local_pv muc lvm q = match q with
  | Qdot _ -> find_global_pv muc q
  | Qident id -> let ovs = Mstr.find_opt id.id_str lvm in
      if ovs = None then find_global_pv muc q else ovs

523 524
let mk_gvars muc lvm old = fun at q ->
  match find_local_pv muc lvm q, at with
525 526 527 528 529 530 531 532 533
  | Some v, Some l -> Some (old l v)
  | None, Some l ->
      begin match q with
      (* normally, we have no reason to call "old" without
         a pvsymbol, but we make an exception for an empty
         ident to check if the label is valid at Tat *)
      | Qident {id_str = ""} -> Opt.map (old l) None
      | _ -> None end
  | v, None -> v
534 535 536

let type_term muc lvm old t =
  let gvars = mk_gvars muc lvm old in
537
  let t = dterm muc gvars None Dterm.denv_empty t in
538
  Dterm.term ~strict:true ~keep_loc:true t
Andrei Paskevich's avatar
Andrei Paskevich committed
539

540 541
let type_fmla muc lvm old f =
  let gvars = mk_gvars muc lvm old in
542
  let f = dterm muc gvars None Dterm.denv_empty f in
543
  Dterm.fmla ~strict:true ~keep_loc:true f
Andrei Paskevich's avatar
Andrei Paskevich committed
544

545 546
let dpre muc pl lvm old =
  let dpre f = type_fmla muc lvm old f in
547 548
  List.map dpre pl

549
let dpost muc ql lvm old ity =
550 551 552
  let dpost (loc,pfl) = match pfl with
    | [{ pat_desc = Ptree.Pwild | Ptree.Ptuple [] }, f] ->
        let v = create_pvsymbol (id_fresh "result") ity in
553
        v, Loc.try3 ~loc type_fmla muc lvm old f
554
    | [{ pat_desc = Ptree.Pvar (id,false) }, f] ->
555 556
        let v = create_pvsymbol (create_user_id id) ity in
        let lvm = Mstr.add id.id_str v lvm in
557
        v, Loc.try3 ~loc type_fmla muc lvm old f
558 559 560 561
    | _ ->
        let v = create_pvsymbol (id_fresh "result") ity in
        let i = { id_str = "(null)"; id_loc = loc; id_lab = [] } in
        let t = { term_desc = Tident (Qident i); term_loc = loc } in
562
        let f = { term_desc = Ptree.Tcase (t, pfl); term_loc = loc } in
563
        let lvm = Mstr.add "(null)" v lvm in
564
        v, Loc.try3 ~loc type_fmla muc lvm old f in
565 566
  List.map dpost ql

567
let dxpost muc ql lvm xsm old =
Andrei Paskevich's avatar
Andrei Paskevich committed
568
  let add_exn (q,pf) m =
569 570 571 572 573
    let xs = match q with
      | Qident i ->
          begin try Mstr.find i.id_str xsm with
          | Not_found -> find_xsymbol muc q end
      | _ -> find_xsymbol muc q in
574
    Mxs.change (fun l -> match pf, l with
Andrei Paskevich's avatar
Andrei Paskevich committed
575 576 577 578
      | Some pf, Some l -> Some (pf :: l)
      | Some pf, None   -> Some (pf :: [])
      | None,    None   -> Some []
      | None,    Some _ -> l) xs m in
579
  let mk_xpost loc xs pfl =
Andrei Paskevich's avatar
Andrei Paskevich committed
580
    if pfl = [] then [] else
581
    dpost muc [loc,pfl] lvm old xs.xs_ity in
582
  let exn_map (loc,xpfl) =
583 584
    let m = List.fold_right add_exn xpfl Mxs.empty in
    Mxs.mapi (fun xs pfl -> mk_xpost loc xs pfl) m in
585
  let add_map ql m =
586 587
    Mxs.union (fun _ l r -> Some (l @ r)) (exn_map ql) m in
  List.fold_right add_map ql Mxs.empty
588 589 590 591 592 593 594

let dreads muc rl lvm =
  let dreads q = match find_local_pv muc lvm q with Some v -> v
    | None -> Loc.errorm ~loc:(qloc q) "Not a variable: %a" print_qualid q in
  List.map dreads rl

let dwrites muc wl lvm =
595 596 597
  let old _ _ = Loc.errorm
    "`at' and `old' cannot be used in the `writes' clause" in
  let dwrites t = type_term muc lvm old t in
598 599 600 601 602 603
  List.map dwrites wl

let find_variant_ls muc q = match find_lsymbol muc.muc_theory q with
  | { ls_args = [u;v]; ls_value = None } as ls when ty_equal u v -> ls
  | s -> Loc.errorm ~loc:(qloc q) "Not an order relation: %a" Pretty.print_ls s

604
let dvariant muc varl lvm _xsm old =
605
  let dvar t = type_term muc lvm old t in
606 607 608
  let dvar (t,q) = dvar t, Opt.map (find_variant_ls muc) q in
  List.map dvar varl

609
let dspec muc sp lvm xsm old ity = {
610 611
  ds_pre     = dpre muc sp.sp_pre lvm old;
  ds_post    = dpost muc sp.sp_post lvm old ity;
612
  ds_xpost   = dxpost muc sp.sp_xpost lvm xsm old;
613 614 615 616 617
  ds_reads   = dreads muc sp.sp_reads lvm;
  ds_writes  = dwrites muc sp.sp_writes lvm;
  ds_checkrw = sp.sp_checkrw;
  ds_diverge = sp.sp_diverge; }

Andrei Paskevich's avatar
Andrei Paskevich committed
618 619 620 621 622
let dspec_no_variant muc sp = match sp.sp_variant with
  | ({term_loc = loc},_)::_ ->
      Loc.errorm ~loc "unexpected 'variant' clause"
  | _ -> dspec muc sp

623
let dassert muc f lvm _xsm old = type_fmla muc lvm old f
624

625
let dinvariant muc f lvm _xsm old = dpre muc f lvm old
626 627 628

(* abstract values *)

629 630
let dparam muc (_,id,gh,pty) =
  Opt.map create_user_id id, gh, dity_of_pty muc pty
631

632 633
let dbinder muc (_,id,gh,opt) =
  Opt.map create_user_id id, gh, dity_of_opt muc opt
634 635 636 637

(* expressions *)

let is_reusable de = match de.de_node with
638
  | DEvar _ | DEsym _ -> true | _ -> false
639 640 641 642 643 644 645 646

let mk_var n de =
  Dexpr.dexpr ?loc:de.de_loc (DEvar (n, de.de_dvty))

let mk_let ~loc n de node =
  let de1 = Dexpr.dexpr ~loc node in
  DElet ((id_user n loc, false, RKnone, de), de1)

647
let update_any kind e = match e.expr_desc with
648 649
  | Ptree.Eany (pl, _, pty, msk, sp) ->
      { e with expr_desc = Ptree.Eany (pl, kind, pty, msk, sp) }
650 651 652 653 654 655
  | _ -> e

let local_kind = function
  | RKfunc | RKpred -> RKlocal
  | k -> k

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
let rec eff_dterm muc denv {term_desc = desc; term_loc = loc} =
  let expr_app loc e el =
    List.fold_left (fun e1 e2 ->
      DEapp (Dexpr.dexpr ~loc e1, e2)) e el
  in
  let qualid_app loc q el =
    let e = try DEsym (find_prog_symbol muc q) with
      | _ -> DEls_pure (find_lsymbol muc.muc_theory q, false) in
    expr_app loc e el
  in
  let qualid_app loc q el = match q with
    | Qident {id_str = n} ->
        (match denv_get_opt denv n with
        | Some d -> expr_app loc d el
        | None -> qualid_app loc q el)
    | _ -> qualid_app loc q el
  in
  Dexpr.dexpr ~loc (match desc with
  | Ptree.Tident q ->
      qualid_app loc q []
  | Ptree.Tidapp (q, [e1]) ->
      qualid_app loc q [eff_dterm muc denv e1]
  | Ptree.Tapply (e1, e2) ->
      DEapp (eff_dterm muc denv e1, eff_dterm muc denv e2)
  | Ptree.Tscope (q, e1) ->
      let muc = open_scope muc "dummy" in
      let muc = import_scope muc (string_list_of_qualid q) in
      DElabel (eff_dterm muc denv e1, Slab.empty)
  | Ptree.Tnamed (Lpos uloc, e1) ->
      DEuloc (eff_dterm muc denv e1, uloc)
  | Ptree.Tnamed (Lstr lab, e1) ->
      DElabel (eff_dterm muc denv e1, Slab.singleton lab)
  | Ptree.Tcast (e1, pty) ->
      let d1 = eff_dterm muc denv e1 in
      DEcast (d1, dity_of_pty muc pty)
  | Ptree.Tat _ -> Loc.errorm ~loc "`at' and `old' cannot be used here"
  | Ptree.Tidapp _ | Ptree.Tconst _ | Ptree.Tinfix _ | Ptree.Tinnfix _
693
  | Ptree.Ttuple _ | Ptree.Tlet _ | Ptree.Tcase _ | Ptree.Tif _
694 695 696 697
  | Ptree.Ttrue | Ptree.Tfalse | Ptree.Tnot _ | Ptree.Tbinop _ | Ptree.Tbinnop _
  | Ptree.Tquant _ | Ptree.Trecord _ | Ptree.Tupdate _ ->
      Loc.errorm ~loc "unsupported effect expression")

698 699 700 701 702
let rec dexpr muc denv {expr_desc = desc; expr_loc = loc} =
  let expr_app loc e el =
    List.fold_left (fun e1 e2 ->
      DEapp (Dexpr.dexpr ~loc e1, e2)) e el
  in
703
  let qualid_app loc q el =
704
    let e = try DEsym (find_prog_symbol muc q) with
705
      | _ -> DEls_pure (find_lsymbol muc.muc_theory q, false) in
706
    expr_app loc e el
707 708 709 710 711 712 713 714
  in
  let qualid_app loc q el = match q with
    | Qident {id_str = n} ->
        (match denv_get_opt denv n with
        | Some d -> expr_app loc d el
        | None -> qualid_app loc q el)
    | _ -> qualid_app loc q el
  in
715 716
  let qualid_app_pure loc q el =
    let e = match find_global_pv muc q with
717
      | Some v -> DEpv_pure v
718
      | None -> DEls_pure (find_lsymbol muc.muc_theory q, true) in
719 720 721 722 723 724 725 726 727
    expr_app loc e el
  in
  let qualid_app_pure loc q el = match q with
    | Qident {id_str = n} ->
        (match denv_get_pure_opt denv n with
        | Some d -> expr_app loc d el
        | None -> qualid_app_pure loc q el)
    | _ -> qualid_app_pure loc q el
  in
728 729 730 731 732 733
  let find_dxsymbol q = match q with
    | Qident {id_str = n} ->
        (try denv_get_exn denv n with _
        -> DEgexn (find_xsymbol muc q))
    | _ -> DEgexn (find_xsymbol muc q)
  in
734
  Dexpr.dexpr ~loc begin match desc with
735 736
  | Ptree.Eident q ->
      qualid_app loc q []
737 738
  | Ptree.Eidpur q ->
      qualid_app_pure loc q []
739 740 741 742 743
  | Ptree.Eidapp (q, el) ->
      qualid_app loc q (List.map (dexpr muc denv) el)
  | Ptree.Eapply (e1, e2) ->
      DEapp (dexpr muc denv e1, dexpr muc denv e2)
  | Ptree.Etuple el ->
744
      let e = DEsym (RS (rs_tuple (List.length el))) in
745
      expr_app loc e (List.map (dexpr muc denv) el)
746 747 748 749 750 751 752 753 754 755 756 757
  | Ptree.Einfix (e1, op1, e23)
  | Ptree.Einnfix (e1, op1, e23) ->
      let apply loc de1 op de2 =
        if op.id_str = "infix <>" then
          let oq = Qident { op with id_str = "infix =" } in
          let dt = qualid_app op.id_loc oq [de1;de2] in
          DEnot (Dexpr.dexpr ~loc dt)
        else
          qualid_app op.id_loc (Qident op) [de1;de2] in
      let rec chain n1 n2 loc de1 op1 = function
        | { expr_desc = Ptree.Einfix (e2, op2, e3); expr_loc = loc23 } ->
            let de2 = dexpr muc denv e2 in
758 759
            let re = is_reusable de2 in
            let v = if re then de2 else mk_var n1 de2 in
760 761 762
            let loc12 = loc_cutoff loc loc23 e2.expr_loc in
            let de12 = Dexpr.dexpr ~loc:loc12 (apply loc12 de1 op1 v) in
            let de23 = Dexpr.dexpr ~loc:loc23 (chain n2 n1 loc23 v op2 e3) in
763 764
            let d = DEand (de12, de23) in
            if re then d else mk_let ~loc n1 de2 d
765 766 767
        | e23 ->
            apply loc de1 op1 (dexpr muc denv e23) in
      chain "q1 " "q2 " loc (dexpr muc denv e1) op1 e23
768 769 770 771 772 773 774 775
  | Ptree.Econst (Number.ConstInt _ as c) ->
      let dty = if Mts.is_empty muc.muc_theory.uc_ranges
                then dity_int else dity_fresh () in
      DEconst(c, dty)
  | Ptree.Econst (Number.ConstReal _ as c) ->
      let dty = if Mts.is_empty muc.muc_theory.uc_floats
                then dity_real else dity_fresh () in
      DEconst(c, dty)
776 777 778
  | Ptree.Erecord fl ->
      let ls_of_rs rs = match rs.rs_logic with
        | RLls ls -> ls | _ -> assert false in