dexpr.ml 45.8 KB
Newer Older
1 2 3
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
4
(*  Copyright 2010-2015   --   INRIA - CNRS - Paris-Sud University  *)
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
(*                                                                  *)
10 11 12 13 14 15 16 17 18 19 20 21
(********************************************************************)

open Stdlib
open Ident
open Ty
open Term
open Ity
open Expr

(** Program types *)

type dity =
Andrei Paskevich's avatar
Andrei Paskevich committed
22 23 24 25
  | Dutv of tvsymbol          (* undestructible "user" type variable *)
  | Dvar of dvar ref          (* destructible "fresh" type variable *)
  | Durg of ity * dity        (* undestructible "user" region, for global refs *)
  | Dreg of dvar ref * dity   (* destructible "fresh" region *)
26 27 28 29
  | Dapp of itysymbol * dity list * dity list
  | Dpur of itysymbol * dity list

and dvar =
Andrei Paskevich's avatar
Andrei Paskevich committed
30 31 32 33 34 35 36
  | Dtvs of tvsymbol          (* unassigned fresh type variable *)
  | Dval of dity              (* destructive binding *)

(* In Dapp, the second dity list only contains Dreg's and Durg's.
   In Dreg and Durg, the dity field is a Dapp of the region's type.
   In Dreg, the dvar field leads to another Dreg or Durg.
   In Durg, the ity field is an Ityreg. *)
37 38 39

type dvty = dity list * dity (* A -> B -> C == ([A;B],C) *)

Andrei Paskevich's avatar
Andrei Paskevich committed
40 41 42
let dity_of_dvty (argl,res) =
  List.fold_right (fun a d -> Dpur (its_func, [a;d])) argl res

43 44
let dvar_fresh n = ref (Dtvs (create_tvsymbol (id_fresh n)))

Andrei Paskevich's avatar
Andrei Paskevich committed
45
let dreg_fresh dity = Dreg (dvar_fresh "rho", dity)
46 47 48 49 50 51 52 53 54 55 56 57

let dity_of_ity ity =
  let hr = Hreg.create 3 in
  let rec dity ity = match ity.ity_node with
    | Ityapp (s,tl,rl) -> Dapp (s, List.map dity tl, List.map dreg rl)
    | Itypur (s,tl)    -> Dpur (s, List.map dity tl)
    | Ityvar v -> Dutv v
    | Ityreg r -> dreg r
  and dreg reg =
    try Hreg.find hr reg with Not_found ->
    let {reg_its = s; reg_args = tl; reg_regs = rl} = reg in
    let d = Dapp (s, List.map dity tl, List.map dreg rl) in
Andrei Paskevich's avatar
Andrei Paskevich committed
58
    let r = dreg_fresh d in Hreg.add hr reg r; r in
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
  dity ity

let reg_of_ity = function
  | {ity_node = Ityreg reg} -> reg
  | _ -> assert false

let rec ity_of_dity = function
  | Dvar ({contents = Dval d})
  | Dreg ({contents = Dval d}, _) ->
      ity_of_dity d
  | Dvar r ->
      let v = create_tvsymbol (id_fresh "xi") in
      r := Dval (Dutv v); ity_var v
  | Dreg (r, d) ->
      let ity = ity_of_dity d in
      r := Dval (Durg (ity, d)); ity
  | Dutv v -> ity_var v
  | Durg (ity,_) -> ity
  | Dapp (s,tl,rl) ->
      let reg_of_dity r = reg_of_ity (ity_of_dity r) in
      ity_app s (List.map ity_of_dity tl) (List.map reg_of_dity rl)
  | Dpur (s,tl) ->
      ity_pur s (List.map ity_of_dity tl)

(** Destructive type unification *)

let rec occur_check v = function
  | Dvar {contents = Dval d} | Dreg (_,d) | Durg (_,d) -> occur_check v d
  | Dvar {contents = Dtvs u} | Dutv u -> if tv_equal u v then raise Exit
  | Dapp (_,dl,_) | Dpur (_,dl) -> List.iter (occur_check v) dl

let rec dity_unify d1 d2 = match d1,d2 with
  | Dvar {contents = Dval d1}, d2
  | d1, Dvar {contents = Dval d2}
  | Durg (_,d1), Durg (_,d2) | Durg (_,d1), Dreg (_,d2)
  | Dreg (_,d1), Durg (_,d2) | Dreg (_,d1), Dreg (_,d2) ->
      dity_unify d1 d2
  | Dvar {contents = Dtvs u},
    Dvar {contents = Dtvs v} when tv_equal u v ->
      ()
  | Dvar ({contents = Dtvs v} as r), d
  | d, Dvar ({contents = Dtvs v} as r) ->
      occur_check v d;
      r := Dval d
  | Dutv u, Dutv v when tv_equal u v ->
      ()
  |(Dapp (s1,dl1,_), Dapp (s2,dl2,_)
Andrei Paskevich's avatar
Andrei Paskevich committed
106
  | Dpur (s1,dl1),   Dpur (s2,dl2)) when its_equal s1 s2 ->
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
      List.iter2 dity_unify dl1 dl2
  | _ -> raise Exit

(** Reunify regions *)

let dtvs_queue : dvar ref Queue.t = Queue.create ()

let unify_queue : (dity * dity) Queue.t = Queue.create ()

let dity_fresh () =
  let r = dvar_fresh "mu" in
  Queue.add r dtvs_queue;
  Dvar r

let rec dity_refresh ht = function
  | Dreg ({contents = Dtvs v},d) ->
      begin try Htv.find ht v with Not_found ->
Andrei Paskevich's avatar
Andrei Paskevich committed
124
      let r = dreg_fresh (dity_refresh ht d) in
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
      Htv.add ht v r; r end
  | Dreg _ -> assert false
  | Dpur (s,dl) ->    Dpur (s, List.map (dity_refresh ht) dl)
  | Dapp (s,dl,rl) -> Dapp (s, List.map (dity_refresh ht) dl,
                               List.map (dity_refresh ht) rl)
  | Dvar {contents = Dval d} -> dity_refresh (Htv.create 3) d
  |(Dvar {contents = Dtvs _} | Dutv _ | Durg _) as d -> d

let dity_refresh d = dity_refresh (Htv.create 3) d

let dity_unify_weak = dity_unify

let dity_unify d1 d2 = dity_unify d1 d2; Queue.add (d1,d2) unify_queue

let rec reunify d1 d2 = match d1,d2 with
  | Dvar {contents = Dval d1}, d2
  | d1, Dvar {contents = Dval d2}
  | Dreg ({contents = Dval d1},_), d2
  | d1, Dreg ({contents = Dval d2},_) ->
      reunify d1 d2
  | Dvar _, Dvar _ | Dutv _, Dutv _ | Durg _, Durg _ ->
      ()
  | Dreg ({contents = Dtvs u},_),
    Dreg ({contents = Dtvs v},_) when tv_equal u v ->
      ()
  | Dreg (r, d1), (Dreg (_, d2) as d)
  | Dreg (r, d1), (Durg (_, d2) as d)
  | (Durg (_, d1) as d), Dreg (r, d2) ->
      reunify d1 d2;
      r := Dval d
  | Dapp (_,dl1,rl1), Dapp (_,dl2,rl2) ->
      List.iter2 reunify dl1 dl2;
      List.iter2 reunify rl1 rl2
  | Dpur (_,dl1), Dpur (_,dl2) ->
      List.iter2 reunify dl1 dl2
  | _ -> assert false

let reunify_regions () =
  Queue.iter (fun r -> match !r with
    | Dval d -> r := Dval (dity_refresh d)
    | Dtvs _ -> ()) dtvs_queue;
  Queue.clear dtvs_queue;
  Queue.iter (fun (d1,d2) -> reunify d1 d2) unify_queue;
  Queue.clear unify_queue

(** Built-in types *)

let dity_int  = Dpur (its_int,  [])
let dity_real = Dpur (its_real, [])
let dity_bool = Dpur (its_bool, [])
let dity_unit = Dpur (its_unit, [])

let dvty_int  = [], dity_int
let dvty_real = [], dity_real
let dvty_bool = [], dity_bool
let dvty_unit = [], dity_unit

(** Pretty-printing *)

let rprinter =
  let sanitizer = Ident.sanitizer Ident.char_to_lalpha Ident.char_to_alnumus in
  Ident.create_ident_printer [] ~sanitizer

let print_args pr fmt tl = if tl <> [] then
  Format.fprintf fmt "@ %a" (Pp.print_list Pp.space pr) tl

let print_regs pr fmt rl = if rl <> [] then
  Format.fprintf fmt "@ <%a>" (Pp.print_list Pp.comma pr) rl

let protect_on x s = if x then "(" ^^ s ^^ ")" else s

let rec print_dity pri fmt = function
  | Dvar {contents = Dval d}
  | Dreg ({contents = Dval d},_) ->
      print_dity pri fmt d
  | Dvar {contents = Dtvs v}
  | Dutv v ->
      Pretty.print_tv fmt v
  | Dreg ({contents = Dtvs v},d) ->
      Format.fprintf fmt (protect_on (pri > 1) "%a@ @@%s")
        (print_dity 0) d (Ident.id_unique rprinter v.tv_name)
  | Durg (ity,d) ->
      Format.fprintf fmt (protect_on (pri > 1) "%a@ @@%s")
        (print_dity 0) d (Ident.id_unique rprinter (reg_of_ity ity).reg_name)
  | Dpur (s,[t1;t2]) when its_equal s its_func ->
      Format.fprintf fmt (protect_on (pri > 0) "%a@ ->@ %a")
        (print_dity 1) t1 (print_dity 0) t2
  | Dpur (s,tl) when is_ts_tuple s.its_ts ->
      Format.fprintf fmt "(%a)" (Pp.print_list Pp.comma (print_dity 0)) tl
214
  | Dpur (s,tl) when its_impure s ->
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      Format.fprintf fmt (protect_on (pri > 1 && tl <> []) "{%a}%a")
        Pretty.print_ts s.its_ts (print_args (print_dity 2)) tl
  | Dpur (s,tl) ->
      Format.fprintf fmt (protect_on (pri > 1 && tl <> []) "%a%a")
        Pretty.print_ts s.its_ts (print_args (print_dity 2)) tl
  | Dapp (s,tl,rl) ->
      Format.fprintf fmt (protect_on (pri > 1) "%a%a%a")
        Pretty.print_ts s.its_ts (print_args (print_dity 2)) tl
          (print_regs (print_dity 0)) rl

let print_dity fmt d = print_dity 0 fmt d

(* Specialization of symbols *)

let specialize_scheme tvs (argl,res) =
  let hv = Htv.create 3 and hr = Htv.create 3 in
  let rec spec_dity = function
    | Durg _ as d -> d
    | Dvar {contents = Dval d} | Dreg ({contents = Dval d},_) -> spec_dity d
    | Dvar {contents = Dtvs v} | Dutv v as d -> get_tv v d
    | Dreg ({contents = Dtvs v},d) -> get_reg v d
    | Dapp (s,dl,rl) -> Dapp (s, List.map spec_dity dl, List.map spec_dity rl)
    | Dpur (s,dl)    -> Dpur (s, List.map spec_dity dl)
  and get_tv v d = try Htv.find hv v with Not_found ->
    let nd = dity_fresh () in
    (* can't return d, might differ in regions *)
    if not (Stv.mem v tvs) then dity_unify_weak nd d;
    Htv.add hv v nd; nd
  and get_reg v d = try Htv.find hr v with Not_found ->
Andrei Paskevich's avatar
Andrei Paskevich committed
244
    let r = dreg_fresh (spec_dity d) in
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    Htv.add hr v r; r in
  List.map spec_dity argl, spec_dity res

let spec_ity hv hr frz ity =
  let rec dity ity = match ity.ity_node with
    | Ityreg r -> dreg r
    | Ityvar v -> if Mtv.mem v frz.isb_tv then Dutv v else get_tv v
    | Ityapp (s,tl,rl) -> Dapp (s, List.map dity tl, List.map dreg rl)
    | Itypur (s,tl)    -> Dpur (s, List.map dity tl)
  and get_tv v = try Htv.find hv v with Not_found ->
    let nd = dity_fresh () in Htv.add hv v nd; nd
  and dreg reg = try Hreg.find hr reg with Not_found ->
    let {reg_its = s; reg_args = tl; reg_regs = rl} = reg in
    let d = Dapp (s, List.map dity tl, List.map dreg rl) in
    let r = if Mreg.mem reg frz.isb_reg then
Andrei Paskevich's avatar
Andrei Paskevich committed
260
      Durg (ity_reg reg, d) else dreg_fresh d in
261 262 263
    Hreg.add hr reg r; r in
  dity ity

Andrei Paskevich's avatar
Andrei Paskevich committed
264
let specialize_pv {pv_ity = ity} =
265 266
  spec_ity (Htv.create 3) (Hreg.create 3) (ity_freeze isb_empty ity) ity

Andrei Paskevich's avatar
Andrei Paskevich committed
267
let specialize_xs {xs_ity = ity} =
268 269
  spec_ity (Htv.create 3) (Hreg.create 3) (ity_freeze isb_empty ity) ity

270
let specialize_rs {rs_cty = cty} =
271 272 273 274 275 276 277
  let hv = Htv.create 3 and hr = Hreg.create 3 in
  let spec ity = spec_ity hv hr cty.cty_freeze ity in
  List.map (fun v -> spec v.pv_ity) cty.cty_args, spec cty.cty_result

(** Patterns *)

type dpattern = {
Andrei Paskevich's avatar
Andrei Paskevich committed
278
  dp_pat  : pre_pattern;
279 280 281 282 283 284 285 286
  dp_dity : dity;
  dp_vars : dity Mstr.t;
  dp_loc  : Loc.position option;
}

type dpattern_node =
  | DPwild
  | DPvar  of preid
287
  | DPapp  of rsymbol * dpattern list
288 289 290 291 292 293 294 295
  | DPor   of dpattern * dpattern
  | DPas   of dpattern * preid
  | DPcast of dpattern * ity

(** Specifications *)

type ghost = bool

Andrei Paskevich's avatar
Andrei Paskevich committed
296
type dbinder = preid option * ghost * dity
297

298 299 300
type register_old = pvsymbol -> string -> pvsymbol

type 'a later = pvsymbol Mstr.t -> register_old -> 'a
301 302 303 304 305 306
  (* specification terms are parsed and typechecked after the program
     expressions, when the types of locally bound program variables are
     already established. *)

type dspec_final = {
  ds_pre     : term list;
307 308 309
  ds_post    : (pvsymbol * term) list;
  ds_xpost   : (pvsymbol * term) list Mexn.t;
  ds_reads   : pvsymbol list;
310 311
  ds_writes  : term list;
  ds_diverge : bool;
312
  ds_checkrw : bool;
313 314
}

315
type dspec = ity -> dspec_final
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  (* Computation specification is also parametrized by the result type.
     All vsymbols in the postcondition clauses in the [ds_post] field
     must have this type. All vsymbols in the exceptional postcondition
     clauses must have the type of the corresponding exception. *)

(** Expressions *)

type dinvariant = term list

type dexpr = {
  de_node : dexpr_node;
  de_dvty : dvty;
  de_loc  : Loc.position option;
}

and dexpr_node =
  | DEvar of string * dvty
333 334
  | DEpv of pvsymbol
  | DErs of rsymbol
335
  | DEconst of Number.constant
336
  | DEapp of dexpr * dexpr
Andrei Paskevich's avatar
Andrei Paskevich committed
337
  | DEfun of dbinder list * dspec later * dexpr
338
  | DEany of dbinder list * dspec later * dity
339 340
  | DElet of dlet_defn * dexpr
  | DErec of drec_defn * dexpr
Andrei Paskevich's avatar
Andrei Paskevich committed
341
  | DEnot of dexpr
342 343
  | DEand of dexpr * dexpr
  | DEor of dexpr * dexpr
344 345
  | DEif of dexpr * dexpr * dexpr
  | DEcase of dexpr * (dpattern * dexpr) list
346
  | DEassign of (dexpr * rsymbol * dexpr) list
347
  | DEwhile of dexpr * dinvariant later * variant list later * dexpr
348
  | DEfor of preid * dexpr * for_direction * dexpr * dinvariant later * dexpr
Andrei Paskevich's avatar
Andrei Paskevich committed
349 350 351
  | DEtry of dexpr * (xsymbol * dpattern * dexpr) list
  | DEraise of xsymbol * dexpr
  | DEghost of dexpr
352
  | DEassert of assertion_kind * term later
Andrei Paskevich's avatar
Andrei Paskevich committed
353 354 355 356
  | DEpure of term later
  | DEabsurd
  | DEtrue
  | DEfalse
357 358 359 360 361
  | DEmark of preid * dexpr
  | DEcast of dexpr * ity
  | DEuloc of dexpr * Loc.position
  | DElabel of dexpr * Slab.t

362
and dlet_defn = preid * ghost * rs_kind * dexpr
363 364 365

and drec_defn = { fds : dfun_defn list }

366
and dfun_defn = preid * ghost * rs_kind *
367
  dbinder list * dspec later * variant list later * dexpr
Andrei Paskevich's avatar
Andrei Paskevich committed
368

369 370 371 372 373 374 375 376 377
(** Environment *)

type denv = {
  frozen : dity list;
  locals : (Stv.t option * dvty) Mstr.t;
}

let denv_empty = { frozen = []; locals = Mstr.empty }

Andrei Paskevich's avatar
Andrei Paskevich committed
378 379
let is_frozen frozen v =
  try List.iter (occur_check v) frozen; false with Exit -> true
380 381 382

let freeze_dvty frozen (argl,res) =
  let rec add l = function
Andrei Paskevich's avatar
Andrei Paskevich committed
383
    | Dreg (_,d) | Durg (_,d)
384 385 386 387 388 389 390 391
    | Dvar { contents = Dval d } -> add l d
    | Dvar { contents = Dtvs _ } as d -> d :: l
    | Dutv _ as d -> d :: l
    | Dapp (_,tl,_) | Dpur (_,tl) -> List.fold_left add l tl in
  List.fold_left add (add frozen res) argl

let free_vars frozen (argl,res) =
  let rec add s = function
Andrei Paskevich's avatar
Andrei Paskevich committed
392
    | Dreg (_,d) | Durg (_,d)
393
    | Dvar { contents = Dval d } -> add s d
Andrei Paskevich's avatar
Andrei Paskevich committed
394 395
    | Dvar { contents = Dtvs v }
    | Dutv v -> if is_frozen frozen v then s else Stv.add v s
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    | Dapp (_,tl,_) | Dpur (_,tl) -> List.fold_left add s tl in
  List.fold_left add (add Stv.empty res) argl

let denv_add_mono { frozen = frozen; locals = locals } id dvty =
  let locals = Mstr.add id.pre_name (None, dvty) locals in
  { frozen = freeze_dvty frozen dvty; locals = locals }

let denv_add_poly { frozen = frozen; locals = locals } id dvty =
  let ftvs = free_vars frozen dvty in
  let locals = Mstr.add id.pre_name (Some ftvs, dvty) locals in
  { frozen = frozen; locals = locals }

let denv_add_rec_mono { frozen = frozen; locals = locals } id dvty =
  let locals = Mstr.add id.pre_name (Some Stv.empty, dvty) locals in
  { frozen = freeze_dvty frozen dvty; locals = locals }

let denv_add_rec_poly { frozen = frozen; locals = locals } frozen0 id dvty =
  let ftvs = free_vars frozen0 dvty in
  let locals = Mstr.add id.pre_name (Some ftvs, dvty) locals in
  { frozen = frozen; locals = locals }

let denv_add_rec denv frozen0 id ((argl,res) as dvty) =
  let rec is_explicit = function
Andrei Paskevich's avatar
Andrei Paskevich committed
419
    | Dreg (_,d) | Durg (_,d)
420 421
    | Dvar { contents = Dval d } -> is_explicit d
    | Dvar { contents = Dtvs _ } -> false
Andrei Paskevich's avatar
Andrei Paskevich committed
422 423
    | Dutv _ -> true
    | Dapp (_,tl,_) | Dpur (_,tl) -> List.for_all is_explicit tl in
424 425 426 427 428 429
  if List.for_all is_explicit argl && is_explicit res
  then denv_add_rec_poly denv frozen0 id dvty
  else denv_add_rec_mono denv id dvty

let denv_add_var denv id dity = denv_add_mono denv id ([], dity)

Andrei Paskevich's avatar
Andrei Paskevich committed
430
let denv_add_let denv (id,_,_,({de_dvty = dvty} as de)) =
431 432 433
  if fst dvty = [] then denv_add_mono denv id dvty else
  let rec is_value de = match de.de_node with
    | DEghost de | DEuloc (de,_) | DElabel (de,_) -> is_value de
434
    | DEvar _ | DErs _ | DEfun _ | DEany _ -> true
435 436 437 438 439 440
    | _ -> false in
  if is_value de
  then denv_add_poly denv id dvty
  else denv_add_mono denv id dvty

let denv_add_args { frozen = frozen; locals = locals } bl =
Andrei Paskevich's avatar
Andrei Paskevich committed
441 442
  let l = List.fold_left (fun l (_,_,t) -> t::l) frozen bl in
  let add s (id,_,t) = match id with
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    | Some {pre_name = n} ->
        Mstr.add_new (Dterm.DuplicateVar n) n (None, ([],t)) s
    | None -> s in
  let s = List.fold_left add Mstr.empty bl in
  { frozen = l; locals = Mstr.set_union s locals }

let denv_add_pat { frozen = frozen; locals = locals } dp =
  let l = Mstr.fold (fun _ t l -> t::l) dp.dp_vars frozen in
  let s = Mstr.map (fun t -> None, ([], t)) dp.dp_vars in
  { frozen = l; locals = Mstr.set_union s locals }

let mk_node n = function
  | Some tvs, dvty -> DEvar (n, specialize_scheme tvs dvty)
  | None,     dvty -> DEvar (n, dvty)

let denv_get denv n =
  mk_node n (Mstr.find_exn (Dterm.UnboundVar n) n denv.locals)

let denv_get_opt denv n =
  Opt.map (mk_node n) (Mstr.find_opt n denv.locals)

(** Unification tools *)

let dity_unify_app ls fn (l1: 'a list) (l2: dity list) =
  try List.iter2 fn l1 l2 with Invalid_argument _ ->
    raise (BadArity (ls, List.length l1))

let dpat_expected_type {dp_dity = dp_dity; dp_loc = loc} dity =
  try dity_unify dp_dity dity with Exit -> Loc.errorm ?loc
    "This pattern has type %a,@ but is expected to have type %a"
    print_dity dp_dity print_dity dity

let dpat_expected_type_weak {dp_dity = dp_dity; dp_loc = loc} dity =
  try dity_unify_weak dp_dity dity with Exit -> Loc.errorm ?loc
    "This pattern has type %a,@ but is expected to have type %a"
    print_dity dp_dity print_dity dity

Andrei Paskevich's avatar
Andrei Paskevich committed
480 481
let dexpr_expected_type {de_dvty = dvty; de_loc = loc} dity =
  let res = dity_of_dvty dvty in
482 483 484 485
  try dity_unify res dity with Exit -> Loc.errorm ?loc
    "This expression has type %a,@ but is expected to have type %a"
    print_dity res print_dity dity

Andrei Paskevich's avatar
Andrei Paskevich committed
486 487
let dexpr_expected_type_weak {de_dvty = dvty; de_loc = loc} dity =
  let res = dity_of_dvty dvty in
488 489 490 491 492 493
  try dity_unify_weak res dity with Exit -> Loc.errorm ?loc
    "This expression has type %a,@ but is expected to have type %a"
    print_dity res print_dity dity

(** Generation of letrec blocks *)

494 495
type pre_fun_defn = preid * ghost * rs_kind * dbinder list *
  dity * (denv -> dspec later * variant list later * dexpr)
496 497 498 499

exception DupId of preid

let drec_defn denv0 prel =
Andrei Paskevich's avatar
Andrei Paskevich committed
500 501
  if prel = [] then invalid_arg "Dexpr.drec_defn: empty function list";
  let add s (id,_,_,_,_,_) = Sstr.add_new (DupId id) id.pre_name s in
502 503
  let _ = try List.fold_left add Sstr.empty prel with DupId id ->
    Loc.errorm ?loc:id.pre_loc "duplicate function name %s" id.pre_name in
Andrei Paskevich's avatar
Andrei Paskevich committed
504 505 506
  let add denv (id,_,_,bl,res,_) =
    if bl = [] then invalid_arg "Dexpr.drec_defn: empty argument list";
    let argl = List.map (fun (_,_,t) -> t) bl in
507 508
    denv_add_rec denv denv0.frozen id (argl,res) in
  let denv1 = List.fold_left add denv0 prel in
Andrei Paskevich's avatar
Andrei Paskevich committed
509
  let parse (id,gh,pk,bl,res,pre) =
510
    let dsp, dvl, de = pre (denv_add_args denv1 bl) in
511
    dexpr_expected_type_weak de res;
512
    (id,gh,pk,bl,dsp,dvl,de) in
513
  let fdl = List.map parse prel in
514
  let add denv (id,_,_,bl,_,_,{de_dvty = dvty}) =
Andrei Paskevich's avatar
Andrei Paskevich committed
515
    (* just in case we linked some polymorphic type var to the outer context *)
516 517 518 519 520 521 522
    let check tv = if is_frozen denv0.frozen tv then Loc.errorm ?loc:id.pre_loc
      "This function is expected to be polymorphic in type variable %a"
      Pretty.print_tv tv in
    begin match Mstr.find_opt id.pre_name denv1.locals with
    | Some (Some tvs, _) -> Stv.iter check tvs
    | Some (None, _) | None -> assert false
    end;
Andrei Paskevich's avatar
Andrei Paskevich committed
523 524
    let argl = List.map (fun (_,_,t) -> t) bl in
    denv_add_poly denv id (argl, dity_of_dvty dvty) in
525 526 527 528 529 530 531 532 533 534 535 536 537
  List.fold_left add denv0 fdl, { fds = fdl }

(** Constructors *)

let dpattern ?loc node =
  let mk_dpat pre dity vars =
    { dp_pat = pre; dp_dity = dity; dp_vars = vars; dp_loc = loc } in
  let dpat = function
    | DPwild ->
        mk_dpat PPwild (dity_fresh ()) Mstr.empty
    | DPvar id ->
        let dity = dity_fresh () in
        mk_dpat (PPvar id) dity (Mstr.singleton id.pre_name dity)
538 539
    | DPapp ({rs_logic = RLls ls} as rs, dpl) when ls.ls_constr > 0 ->
        let argl, res = specialize_rs rs in
540 541 542 543 544
        dity_unify_app ls dpat_expected_type dpl argl;
        let join n _ _ = raise (Dterm.DuplicateVar n) in
        let add acc dp = Mstr.union join acc dp.dp_vars in
        let vars = List.fold_left add Mstr.empty dpl in
        let ppl = List.map (fun dp -> dp.dp_pat) dpl in
545 546 547
        mk_dpat (PPapp (rs, ppl)) res vars
    | DPapp (rs,_) ->
        raise (ConstructorExpected rs);
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    | DPor (dp1,dp2) ->
        dpat_expected_type dp2 dp1.dp_dity;
        let join n dity1 dity2 = try dity_unify dity1 dity2; Some dity1
          with Exit -> Loc.errorm ?loc
            "Variable %s has type %a,@ but is expected to have type %a"
            n print_dity dity1 print_dity dity2 in
        let vars = Mstr.union join dp1.dp_vars dp2.dp_vars in
        mk_dpat (PPor (dp1.dp_pat, dp2.dp_pat)) dp1.dp_dity vars
    | DPas (dp, ({pre_name = n} as id)) ->
        let { dp_pat = pat; dp_dity = dity; dp_vars = vars } = dp in
        let vars = Mstr.add_new (Dterm.DuplicateVar n) n dity vars in
        mk_dpat (PPas (pat, id)) dity vars
    | DPcast (dp, ity) ->
        dpat_expected_type_weak dp (dity_of_ity ity);
        dp
  in
  Loc.try1 ?loc dpat node

let dexpr ?loc node =
  let get_dvty = function
    | DEvar (_,dvty) ->
569
        dvty
570
    | DEpv pv ->
571
        [], specialize_pv pv
572
    | DErs rs ->
573
        specialize_rs rs
574
    | DEconst (Number.ConstInt _) ->
575
        dvty_int
576
    | DEconst (Number.ConstReal _) ->
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
        dvty_real
    | DEapp ({de_dvty = (arg::argl, res)}, de2) ->
        dexpr_expected_type de2 arg;
        argl, res
    | DEapp ({de_dvty = ([],res)} as de1, de2) ->
        let f,a,r = match specialize_rs rs_func_app with
          | [f;a],r -> f,a,r | _ -> assert false in
        begin try dity_unify res f with Exit ->
          let rec down n de = match de.de_node with
            | DEapp (de,_) -> down (succ n) de
            | _ when n = 0 -> Loc.errorm ?loc:de.de_loc
                "This expression has type %a,@ it cannot be applied"
                print_dity (dity_of_dvty de.de_dvty)
            | _ -> Loc.errorm ?loc:de.de_loc
                "This expression has type %a,@ but is applied to %d arguments"
                print_dity (dity_of_dvty de.de_dvty) (succ n) in
          down 0 de1
        end;
        dexpr_expected_type de2 a;
        [], r
597
    | DEfun (bl,_,de) ->
598
        List.map (fun (_,_,t) -> t) bl, dity_of_dvty de.de_dvty
599
    | DEany (bl,_,res) ->
600
        List.map (fun (_,_,t) -> t) bl, res
601 602
    | DElet (_,de)
    | DErec (_,de) ->
603
        de.de_dvty
604 605
    | DEnot de ->
        dexpr_expected_type de dity_bool;
606 607 608
        dvty_bool
    | DEand (de1,de2)
    | DEor (de1,de2) ->
609 610
        dexpr_expected_type de1 dity_bool;
        dexpr_expected_type de2 dity_bool;
611
        dvty_bool
612 613 614 615 616
    | DEif (de1,de2,de3) ->
        let res = dity_fresh () in
        dexpr_expected_type de1 dity_bool;
        dexpr_expected_type de2 res;
        dexpr_expected_type de3 res;
617
        [], res
618
    | DEcase (_,[]) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
619
        invalid_arg "Dexpr.dexpr: empty branch list in DEcase"
620 621 622 623
    | DEcase (de,bl) ->
        let ety = dity_fresh () in
        let res = dity_fresh () in
        dexpr_expected_type de ety;
624
        List.iter (fun (dp,de) ->
625
          dpat_expected_type dp ety;
626
          dexpr_expected_type de res) bl;
627
        [], res
628
    | DEassign al ->
629 630 631
        List.iter (fun (de1,rs,de2) ->
          let argl, res = specialize_rs rs in
          let ls = match rs.rs_logic with RLls ls -> ls
632 633 634
            | _ -> invalid_arg "Dexpr.dexpr: not a field" in
          dity_unify_app ls dexpr_expected_type [de1] argl;
          dexpr_expected_type_weak de2 res) al;
635 636
        dvty_unit
    | DEwhile (de1,_,_,de2) ->
637
        dexpr_expected_type de1 dity_bool;
638
        dexpr_expected_type de2 dity_unit;
639
        dvty_unit
640 641 642 643
    | DEfor (_,de_from,_,de_to,_,de) ->
        dexpr_expected_type de_from dity_int;
        dexpr_expected_type de_to dity_int;
        dexpr_expected_type de dity_unit;
644
        dvty_unit
645
    | DEtry (_,[]) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
646
        invalid_arg "Dexpr.dexpr: empty branch list in DEtry"
647 648 649
    | DEtry (de,bl) ->
        let res = dity_fresh () in
        dexpr_expected_type de res;
650 651 652
        List.iter (fun (xs,dp,de) ->
          dpat_expected_type dp (specialize_xs xs);
          dexpr_expected_type de res) bl;
653
        [], res
654 655
    | DEraise (xs,de) ->
        dexpr_expected_type de (specialize_xs xs);
656
        [], dity_fresh ()
657
    | DEghost de ->
658
        de.de_dvty
659
    | DEassert _ ->
660
        dvty_unit
661 662
    | DEpure _
    | DEabsurd ->
663
        [], dity_fresh ()
664 665
    | DEtrue
    | DEfalse ->
666
        dvty_bool
667 668
    | DEcast (de,ity) ->
        dexpr_expected_type_weak de (dity_of_ity ity);
669
        de.de_dvty
670
    | DEmark (_,de)
671 672
    | DEuloc (de,_)
    | DElabel (de,_) ->
673 674 675
        de.de_dvty in
  let dvty = Loc.try1 ?loc get_dvty node in
  { de_node = node; de_dvty = dvty; de_loc = loc }
676 677 678 679 680 681 682

(** Final stage *)

(** Binders *)

let binders bl =
  let sn = ref Sstr.empty in
683
  let binder (id, ghost, dity) =
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
    let id = match id with
      | Some ({pre_name = n} as id) ->
          let exn = match id.pre_loc with
            | Some loc -> Loc.Located (loc, Dterm.DuplicateVar n)
            | None -> Dterm.DuplicateVar n in
          sn := Sstr.add_new exn n !sn; id
      | None -> id_fresh "_" in
    create_pvsymbol id ~ghost (ity_of_dity dity) in
  List.map binder bl

(** Specifications *)

let to_fmla f = match f.t_ty with
  | None -> f
  | Some ty when ty_equal ty ty_bool -> t_equ f t_bool_true
  | _ -> Loc.error ?loc:f.t_loc Dterm.FmlaExpected

701 702 703 704
let create_assert = to_fmla

let create_invariant pl = List.map to_fmla pl

705 706
let create_post ity ql = List.map (fun (v,f) ->
  ity_equal_check ity v.pv_ity; Ity.create_post v.pv_vs (to_fmla f)) ql
707

708
let create_xpost xql = Mexn.mapi (fun xs ql -> create_post xs.xs_ity ql) xql
709 710 711

(** User effects *)

712 713 714 715 716 717
let rec effect_of_term t =
  let quit () = Loc.errorm ?loc:t.t_loc "unsupported effect expression" in
  match t.t_node with
  | Tapp (fs, [ta]) ->
      let v, ity, fa = effect_of_term ta in
      let ity = match fa with
718
        | Some {rs_cty = {cty_args = [arg]; cty_result = res}} ->
719 720 721
            ity_full_inst (ity_match isb_empty arg.pv_ity ity) res
        | Some _ -> assert false
        | None -> ity in
722
      begin try match ity.ity_node, restore_rs fs with
Andrei Paskevich's avatar
Andrei Paskevich committed
723 724
        | Ityreg {reg_its = ts}, ({rs_field = Some f} as rs)
          when List.exists (pv_equal f) ts.its_mfields -> v, ity, Some rs
725
        | _, {rs_cty={cty_args=[arg]; cty_result=res; cty_freeze=frz}} ->
726 727 728 729 730 731
            v, ity_full_inst (ity_match frz arg.pv_ity ity) res, None
        | _ -> quit () with Not_found -> quit () end
  | Tvar v ->
      let v = try restore_pv v with Not_found -> quit () in
      v, v.pv_ity, None
  | _ -> quit ()
732 733

let effect_of_dspec dsp =
734
  let pvs = Spv.of_list dsp.ds_reads in
735
  let add_write (l,eff) t = match effect_of_term t with
736 737
    | v, {ity_node = Ityreg reg}, fd ->
        let fs = match fd with
738
          | Some fd -> Spv.singleton (Opt.get fd.rs_field)
739
          | None -> Spv.of_list reg.reg_its.its_mfields in
740 741 742
        let rd = Spv.singleton v and wr = Mreg.singleton reg fs in
        let e = Loc.try2 ?loc:t.t_loc eff_write rd wr in
        (e,t)::l, eff_union_par eff e
743
    | _ ->
744
        Loc.errorm ?loc:t.t_loc "mutable expression expected" in
745 746 747 748
  let wl, eff = List.fold_left add_write ([], eff_read pvs) dsp.ds_writes in
  let eff = Mexn.fold (fun xs _ eff -> eff_raise eff xs) dsp.ds_xpost eff in
  let eff = if dsp.ds_diverge then eff_diverge eff else eff in
  wl, eff
749

750 751
(* TODO: add warnings for empty postconditions (anywhere)
    and empty exceptional postconditions (toplevel). *)
Andrei Paskevich's avatar
Andrei Paskevich committed
752
let check_spec dsp ecty e =
753 754 755
  let bad_write weff eff = not (Mreg.submap (fun _ s1 s2 -> Spv.subset s1 s2)
                                            weff.eff_writes eff.eff_writes) in
  let bad_raise xeff eff = not (Sexn.subset xeff.eff_raises eff.eff_raises) in
756
  (* computed effect vs user effect *)
Andrei Paskevich's avatar
Andrei Paskevich committed
757
  let check_rwd = dsp.ds_checkrw in
758
  let uwrl, ue = effect_of_dspec dsp in
759 760
  let ucty = create_cty ecty.cty_args ecty.cty_pre ecty.cty_post
    ecty.cty_xpost ecty.cty_oldies ue ecty.cty_result in
761 762
  let ueff = ucty.cty_effect and eeff = ecty.cty_effect in
  let urds = ueff.eff_reads and erds = eeff.eff_reads in
763
  (* check that every user effect actually happens *)
764 765 766 767 768 769 770 771 772
  if not (Spv.subset urds erds) then Loc.errorm ?loc:e.e_loc
    "variable@ %a@ does@ not@ occur@ in@ this@ expression"
    Pretty.print_vs (Spv.choose (Spv.diff urds erds)).pv_vs;
  if bad_write ueff eeff then List.iter (fun (weff,t) ->
    if bad_write weff eeff then Loc.errorm ?loc:t.t_loc
      "this@ write@ effect@ does@ not@ happen@ in@ the@ expression") uwrl;
  if bad_raise ueff eeff then Loc.errorm ?loc:e.e_loc
    "this@ expression@ does@ not@ raise@ exception@ %a"
    print_xs (Sexn.choose (Sexn.diff ueff.eff_raises eeff.eff_raises));
773
  if ueff.eff_oneway && not eeff.eff_oneway then Loc.errorm ?loc:e.e_loc
774
    "this@ expression@ does@ not@ diverge";
775
  (* check that every computed effect is listed *)
776 777 778 779 780
  if check_rwd && not (Spv.subset erds urds) then Spv.iter (fun v ->
    Loc.errorm ?loc:e.e_loc
      "this@ expression@ depends@ on@ variable@ %a@ left@ out@ in@ \
      the@ specification" Pretty.print_vs v.pv_vs) (Spv.diff erds urds);
  if check_rwd && bad_write eeff ueff then
781
    Loc.errorm ?loc:(e_locate_effect (fun eff -> bad_write eff ueff) e)
782 783
      "this@ expression@ produces@ an@ unlisted@ write@ effect";
  if ecty.cty_args <> [] && bad_raise eeff ueff then Sexn.iter (fun xs ->
784
    Loc.errorm ?loc:(e_locate_effect (fun eff -> Sexn.mem xs eff.eff_raises) e)
785
      "this@ expression@ raises@ unlisted@ exception@ %a"
786
      print_xs xs) (Sexn.diff eeff.eff_raises ueff.eff_raises);
787 788
  if check_rwd && eeff.eff_oneway && not ueff.eff_oneway then
    Loc.errorm ?loc:(e_locate_effect (fun eff -> eff.eff_oneway) e)
789 790
      "this@ expression@ may@ diverge,@ but@ this@ is@ not@ \
        stated@ in@ the@ specification"
791

Andrei Paskevich's avatar
Andrei Paskevich committed
792
let check_aliases recu c =
793 794 795
  let rds_regs = c.cty_freeze.isb_reg in
  let report r _ _ =
    if Mreg.mem r rds_regs then let spv = Spv.filter
796
        (fun v -> ity_r_occurs r v.pv_ity) (cty_reads c) in
797
      Loc.errorm "The type of this function contains an alias with \
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        external variable %a" print_pv (Spv.choose spv)
    else Loc.errorm "The type of this function contains an alias" in
  (* we allow the value in a non-recursive function to contain
     regions coming the function's arguments, but not from the
     context. It is sometimes useful to write a function around
     a constructor or a projection. For recursive functions, we
     impose the full non-alias discipline, to ensure the safety
     of region polymorphism (see add_rec_mono). We do not track
     aliases inside the type of an argument or a result, which
     may break the type inference, but we have a safety net
     type checking in Expr. *)
  let add_ity regs ity =
    let frz = ity_freeze isb_empty ity in
    Mreg.union report regs frz.isb_reg in
  let add_arg regs v = add_ity regs v.pv_ity in
  let regs = List.fold_left add_arg rds_regs c.cty_args in
  ignore (add_ity (if recu then regs else rds_regs) c.cty_result)
815

816
let check_fun rsym dsp e =
Andrei Paskevich's avatar
Andrei Paskevich committed
817
  let c,e = match e with
818
    | { c_node = Cfun e; c_cty = c } -> c,e
Andrei Paskevich's avatar
Andrei Paskevich committed
819 820 821 822 823 824 825
    | _ -> invalid_arg "Dexpr.check_fun" in
  let c = match rsym with
    | Some s -> s.rs_cty
    | None -> c in
  check_spec dsp c e;
  check_aliases (rsym <> None) c

826 827
(** Environment *)

Andrei Paskevich's avatar
Andrei Paskevich committed
828
type env = {
829
  rsm : rsymbol Mstr.t;
830
  pvm : pvsymbol Mstr.t;
831
  old : (pvsymbol Mstr.t * (let_defn * pvsymbol) Hpv.t) Mstr.t;
832 833
}

834
let env_empty = {
835
  rsm = Mstr.empty;
836
  pvm = Mstr.empty;
837
  old = Mstr.empty;
838 839
}

840 841 842
exception UnboundLabel of string

let find_old pvm (ovm,old) v =
843
  if v.pv_ity.ity_pure then v else
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
  let n = v.pv_vs.vs_name.id_string in
  (* if v is top-level, both ov and pv are None.
     If v is local, ov and pv must be equal to v.
     If they are not equal, then v is defined under the label,
     so we return v and do not register an "oldie" for it. *)
  let ov = Mstr.find_opt n ovm in
  let pv = Mstr.find_opt n pvm in
  if not (Opt.equal pv_equal ov pv) then v
  else match Hpv.find_opt old v with
    | Some (_,o) -> o
    | None ->
        let e = e_pure (t_var v.pv_vs) in
        let id = id_clone v.pv_vs.vs_name in
        let ld = let_var id ~ghost:true e in
        Hpv.add old v ld; snd ld

let register_old env v l =
  find_old env.pvm (Mstr.find_exn (UnboundLabel l) l env.old) v

let get_later env later = later env.pvm (register_old env)

let add_label ({pvm = pvm; old = old} as env) l =
  let ht = Hpv.create 3 in
  { env with old = Mstr.add l (pvm, ht) old }, ht

Andrei Paskevich's avatar
Andrei Paskevich committed
869
let rebase_old {pvm = pvm} preold old fvs =
870 871 872 873
  let rebase v (_,{pv_vs = o}) sbs =
    if not (Mvs.mem o fvs) then sbs else match preold with
      | Some preold ->
          Mvs.add o (t_var (find_old pvm preold v).pv_vs) sbs
874
      | None -> raise (UnboundLabel "0") in
875 876
  Hpv.fold rebase old Mvs.empty

Andrei Paskevich's avatar
Andrei Paskevich committed
877
let rebase_pre env preold old pl =
878 879
  let pl = List.map to_fmla pl in
  let fvs = List.fold_left t_freevars Mvs.empty pl in
Andrei Paskevich's avatar
Andrei Paskevich committed
880
  let sbs = rebase_old env preold old fvs in
881 882
  List.map (t_subst sbs) pl

Andrei Paskevich's avatar
Andrei Paskevich committed
883
let rebase_variant env preold old varl =
884 885
  let add s (t,_) = t_freevars s t in
  let fvs = List.fold_left add Mvs.empty varl in
Andrei Paskevich's avatar
Andrei Paskevich committed
886
  let sbs = rebase_old env preold old fvs in
887 888 889
  let conv (t,rel) = t_subst sbs t, rel in
  List.map conv varl

890 891 892 893
let get_oldies old =
  Hpv.fold (fun v (_,o) sbs -> Mpv.add o v sbs) old Mpv.empty

let add_rsymbol ({rsm = rsm; pvm = pvm} as env) rs =
894
  let n = rs.rs_name.id_string in
895 896 897 898
  let pvm = match rs.rs_logic with
    | RLpv pv -> Mstr.add n pv pvm
    | _ -> pvm in
  { env with rsm = Mstr.add n rs rsm; pvm = pvm }
899

900
let add_pvsymbol ({pvm = pvm} as env) pv =
901
  let n = pv.pv_vs.vs_name.id_string in
902
  { env with pvm = Mstr.add n pv pvm }
903

904 905
let add_pv_map ({pvm = pvm} as env) vm =
  { env with pvm = Mstr.set_union vm pvm }
906 907 908 909 910

let add_binders env pvl = List.fold_left add_pvsymbol env pvl

(** Abstract values *)

Andrei Paskevich's avatar
Andrei Paskevich committed
911 912 913 914
let cty_of_spec env bl dsp dity =
  let ity = ity_of_dity dity in
  let bl = binders bl in
  let env = add_binders env bl in
915 916
  let preold = Mstr.find_opt "0" env.old in
  let env, old = add_label env "0" in
917
  let dsp = get_later env dsp ity in
918
  let _, eff = effect_of_dspec dsp in
919
  let eff = eff_reset_overwritten eff in
Andrei Paskevich's avatar
Andrei Paskevich committed
920
  let p = rebase_pre env preold old dsp.ds_pre in
921
  let q = create_post ity dsp.ds_post in
Andrei Paskevich's avatar
Andrei Paskevich committed
922
  let xq = create_xpost dsp.ds_xpost in
923
  create_cty bl p q xq (get_oldies old) eff ity
924 925 926

(** Expressions *)

Andrei Paskevich's avatar
Andrei Paskevich committed
927 928 929 930
let warn_unused s loc =
  if s = "" || s.[0] <> '_' then
  Warning.emit ?loc "unused variable %s" s

931
let check_used_pv e pv = if not (Spv.mem pv e.e_effect.eff_reads) then
Andrei Paskevich's avatar
Andrei Paskevich committed
932
  warn_unused pv.pv_vs.vs_name.id_string pv.pv_vs.vs_name.id_loc
933

934 935 936 937
let e_let_check ld e = match ld with
  | LDvar (v,_) -> check_used_pv e v; e_let ld e
  | _           -> e_let ld e

938 939
let rec strip uloc labs de = match de.de_node with
  | DEcast (de,_) -> strip uloc labs de
940
  | DEuloc (de,loc) -> strip (Some (Some loc)) labs de
941 942 943
  | DElabel (de,s) -> strip uloc (Slab.union labs s) de
  | _ -> uloc, labs, de

944 945 946 947 948 949 950 951 952
let get_pv env n = Mstr.find_exn (Dterm.UnboundVar n) n env.pvm
let get_rs env n = Mstr.find_exn (Dterm.UnboundVar n) n env.rsm

let rec expr uloc env ({de_loc = loc} as de) =
  let uloc, labs, de = strip uloc Slab.empty de in
  let e = Loc.try3 ?loc try_expr uloc env de in
  let loc = Opt.get_def loc uloc in
  if loc = None && Slab.is_empty labs
  then e else e_label ?loc labs e
Andrei Paskevich's avatar
Andrei Paskevich committed
953

954
and cexp uloc env ghost ({de_loc = loc} as de) =
955
  let uloc, labs, de = strip uloc Slab.empty de in
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
  if not (Slab.is_empty labs) then Warning.emit ?loc
    "Ignoring labels over a higher-order expression";
  Loc.try4 ?loc try_cexp uloc env ghost de

and try_cexp uloc env ghost de0 = match de0.de_node with
  | DEvar _ | DErs _ | DEapp _ ->
      let app (ldl,c) el =
        let argl, res = de0.de_dvty in
        ext_c_app (ldl, c_ghostify ghost c) el
          (List.map ity_of_dity argl) (ity_of_dity res) in
      let rec down de el = match de.de_node with
        | DEapp (de1,de2) -> down de1 (expr uloc env de2 :: el)
        | DEvar (n,_) -> app (ext_c_sym (get_rs env n)) el
        | DErs s -> app (ext_c_sym s) el
        | _ -> app (cexp uloc env ghost de) el in
      down de0 []
  | DEfun (bl,dsp,de) ->
973 974
      let dvl _ _ = [] in
      let c, dsp, _ = lambda uloc env (binders bl) dsp dvl de in
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
      check_fun None dsp c;
      [], c_ghostify ghost c
  | DEany (bl,dsp,dity) ->
      [], c_ghostify ghost (c_any (cty_of_spec env bl dsp dity))
  | DElet ((_,_,_,{de_dvty = ([],_)}) as dldf,de) ->
      let ld, env = var_defn uloc env ghost dldf in
      let ldl, c = cexp uloc env ghost de in
      ld::ldl, c
  | DElet (dldf,de) ->
      let ldl0, env = sym_defn uloc env ghost dldf in
      let ldl, c = cexp uloc env ghost de in
      ldl0 @ ldl, c
  | DErec (drdf,de) ->
      let ld, env = rec_defn uloc env ghost drdf in
      let ldl, c = cexp uloc env ghost de in
      ld::ldl, c
  | DEghost de -> cexp uloc env true de
  | DEmark _ ->
      Loc.errorm "Marks are not allowed over higher-order expressions"
  | DEpv _ | DEconst _ | DEnot _ | DEand _ | DEor _ | DEif _ | DEcase _
  | DEassign _ | DEwhile _ | DEfor _ | DEtry _ | DEraise _ | DEassert _
  | DEpure _ | DEabsurd | DEtrue | DEfalse -> assert false (* expr-only *)
  | DEcast _ | DEuloc _ | DElabel _ -> assert false (* already stripped *)

and try_expr uloc env ({de_dvty = argl,res} as de0) =
1000 1001
  match de0.de_node with
  | DEvar (n,_) when argl = [] ->
1002
      e_var (get_pv env n)
Andrei Paskevich's avatar
Andrei Paskevich committed
1003 1004
  | DEpv v ->
      e_var v
1005 1006
  | DEconst c ->
      e_const c
1007
  | DEapp ({de_dvty = ([],_)} as de1, de2) ->
1008 1009 1010 1011 1012 1013 1014 1015 1016
      let e1 = expr uloc env de1 in
      let e2 = expr uloc env de2 in
      e_app rs_func_app [e1; e2] [] (ity_of_dity res)
  | DEvar _ | DErs _ | DEapp _ | DEfun _ | DEany _ ->
      let ldl,c = try_cexp uloc env false de0 in
      List.fold_right e_let_check ldl (e_exec c)
  | DElet ((id,_,_,{de_dvty = ([],_)}) as dldf,de) ->
      let ld, env = var_defn uloc env false dldf in
      let e2 = expr uloc env de in
Andrei Paskevich's avatar
Andrei Paskevich committed
1017
      let e2 =