vc.ml 66.3 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 9 10 11
(*                                                                  *)
(*  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.                           *)
(*                                                                  *)
(********************************************************************)

Guillaume Melquiond's avatar
Guillaume Melquiond committed
12
open Wstdlib
Andrei Paskevich's avatar
Andrei Paskevich committed
13 14 15 16 17 18 19 20
open Ident
open Ty
open Term
open Decl
open Ity
open Expr
open Pdecl

Andrei Paskevich's avatar
Andrei Paskevich committed
21 22
(* basic tools *)

23
let debug_vc = Debug.register_info_flag "vc_debug"
Andrei Paskevich's avatar
Vc: wip  
Andrei Paskevich committed
24 25
  ~desc:"Print@ details@ of@ verification@ conditions@ generation."

26 27 28
let debug_reflow = Debug.register_info_flag "vc_reflow"
  ~desc:"Debug@ elimination@ of@ the@ dead@ code@ in@ VC."

Andrei Paskevich's avatar
Andrei Paskevich committed
29
let debug_sp = Debug.register_flag "vc_sp"
30 31
  ~desc:"Use@ 'Efficient@ Weakest@ Preconditions'@ for@ verification."

32
let debug_no_eval = Debug.register_flag "vc_no_eval"
Andrei Paskevich's avatar
Andrei Paskevich committed
33 34
  ~desc:"Do@ not@ simplify@ pattern@ matching@ on@ record@ datatypes@ in@ VCs."

35 36
let debug_ignore_diverges = Debug.register_info_flag "ignore_missing_diverges"
  ~desc:"Suppress@ warnings@ on@ missing@ diverges."
37

Andrei Paskevich's avatar
Andrei Paskevich committed
38 39
let case_split = Ident.create_attribute "case_split"
let add_case t = t_attr_add case_split t
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
40

41 42 43 44
let clone_pv loc {pv_vs = {vs_name = id; vs_ty = ty}} =
  (* we do not preserve the location of the initial pv
     in the new variable for SP, because we do not want
     to require a model for it and rely on "model_vc_*"
Andrei Paskevich's avatar
Andrei Paskevich committed
45 46
     attributes to produce new, correctly located, variables *)
  let id = id_fresh ~attrs:id.id_attrs ?loc id.id_string in
47
  create_vsymbol id ty
Andrei Paskevich's avatar
Andrei Paskevich committed
48

49
let pv_is_unit v = ity_equal v.pv_ity ity_unit
50

51 52 53 54 55 56 57
let pv_of_ity s ity = create_pvsymbol (id_fresh s) ity

let res_of_post ity = function
  | q::_ -> create_pvsymbol (clone_post_result q) ity
  | _ -> pv_of_ity "result" ity

let res_of_cty cty = res_of_post cty.cty_result cty.cty_post
Andrei Paskevich's avatar
Andrei Paskevich committed
58

Andrei Paskevich's avatar
Andrei Paskevich committed
59
let proxy_of_expr =
Andrei Paskevich's avatar
Andrei Paskevich committed
60 61
  let attrs = Sattr.singleton proxy_attr in fun e ->
  let id = id_fresh ?loc:e.e_loc ~attrs "o" in
62
  create_pvsymbol id e.e_ity
63

Andrei Paskevich's avatar
Andrei Paskevich committed
64 65 66 67
let sp_attr = Ident.create_attribute "vc:sp"
let wp_attr = Ident.create_attribute "vc:wp"
let wb_attr = Ident.create_attribute "vc:white_box"
let kp_attr = Ident.create_attribute "vc:keep_precondition"
68
let nt_attr = Ident.create_attribute "vc:divergent"
69

70 71 72
let vc_attrs =
  Sattr.add nt_attr (Sattr.add kp_attr (Sattr.add wb_attr
  (Sattr.add sp_attr (Sattr.add wp_attr Sattr.empty))))
73

74 75 76 77
(* VCgen environment *)

type vc_env = {
  known_map : Pdecl.known_map;
78
  ts_ranges : Theory.tdecl Mts.t;
79 80 81 82 83 84
  ps_int_le : lsymbol;
  ps_int_ge : lsymbol;
  ps_int_lt : lsymbol;
  ps_int_gt : lsymbol;
  fs_int_pl : lsymbol;
  fs_int_mn : lsymbol;
85
  ps_wf_acc : lsymbol;
86 87
  exn_count : int ref;
  divergent : bool;
88 89
}

90
let mk_env {Theory.th_export = ns_int} {Theory.th_export = ns_acc} kn tuc = {
91
  known_map = kn;
92
  ts_ranges = tuc.Theory.uc_ranges;
93 94 95 96 97 98
  ps_int_le = Theory.ns_find_ls ns_int [Ident.op_infix "<="];
  ps_int_ge = Theory.ns_find_ls ns_int [Ident.op_infix ">="];
  ps_int_lt = Theory.ns_find_ls ns_int [Ident.op_infix "<"];
  ps_int_gt = Theory.ns_find_ls ns_int [Ident.op_infix ">"];
  fs_int_pl = Theory.ns_find_ls ns_int [Ident.op_infix "+"];
  fs_int_mn = Theory.ns_find_ls ns_int [Ident.op_infix "-"];
99
  ps_wf_acc = Theory.ns_find_ls ns_acc ["acc"];
100
  exn_count = ref 0;
101
  divergent = false;
102
}
Andrei Paskevich's avatar
Andrei Paskevich committed
103

104 105 106 107 108 109 110 111
let acc env r t =
  let ps = env.ps_wf_acc in
  if not (Mid.mem ps.ls_name env.known_map) then
    Loc.errorm ?loc:t.t_loc "please import relations.WellFounded";
  let ty = t_type t in
  let r = t_closure r [ty; ty] None in
  ps_app ps [r; t]

112 113 114
(* every exception-catching clause is represented by
   a unique integer, so that we can move code inside
   try-with expressions without capturing exceptions *)
115 116 117 118 119
let new_exn env = incr env.exn_count; !(env.exn_count)

(* FIXME: cannot verify int.why because of a cyclic dependency.
   int.Int is used for the "for" loops and for integer variants.
   We should be able to extract the necessary lsymbols from kn. *)
120 121 122 123
let mk_env env kn tuc =
  let th_int = Env.read_theory env ["int"] "Int" in
  let th_wf  = Env.read_theory env ["relations"] "WellFounded" in
  mk_env th_int th_wf kn tuc
Andrei Paskevich's avatar
Andrei Paskevich committed
124

125 126 127 128 129 130
let int_of_range env ty =
  let td = Mts.find ty env.ts_ranges in
  match td.Theory.td_node with
  | Theory.Meta (_, [_; Theory.MAls s]) -> s
  | _ -> assert false

Andrei Paskevich's avatar
Andrei Paskevich committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
(* explanation attributes *)

let expl_pre       = Ident.create_attribute "expl:precondition"
let expl_post      = Ident.create_attribute "expl:postcondition"
let expl_xpost     = Ident.create_attribute "expl:exceptional postcondition"
let expl_assume    = Ident.create_attribute "expl:assumption"
let expl_assert    = Ident.create_attribute "expl:assertion"
let expl_check     = Ident.create_attribute "expl:check"
let expl_lemma     = Ident.create_attribute "expl:lemma"
let expl_absurd    = Ident.create_attribute "expl:unreachable point"
let expl_for_bound = Ident.create_attribute "expl:loop bounds"
let expl_off_bound = Ident.create_attribute "expl:out of loop bounds"
let expl_loop_init = Ident.create_attribute "expl:loop invariant init"
let expl_loop_keep = Ident.create_attribute "expl:loop invariant preservation"
let expl_loop_vari = Ident.create_attribute "expl:loop variant decrease"
let expl_variant   = Ident.create_attribute "expl:variant decrease"
let expl_type_inv  = Ident.create_attribute "expl:type invariant"
148
let expl_divergent = Ident.create_attribute "expl:termination"
Andrei Paskevich's avatar
Andrei Paskevich committed
149 150 151 152 153 154 155 156 157 158 159 160 161

let attrs_has_expl attrs =
  Sattr.exists (fun a -> Strings.has_prefix "expl:" a.attr_string) attrs

let annot_attrs = Sattr.add stop_split (Sattr.singleton annot_attr)

(* TODO: remove this line, and use "annot_attr" instead *)
let annot_attrs = Sattr.add Ident.model_vc_attr annot_attrs

let vc_expl loc attrs expl f =
  let attrs = Sattr.union annot_attrs (Sattr.union attrs f.t_attrs) in
  let attrs = if attrs_has_expl attrs then attrs else Sattr.add expl attrs in
  t_attr_set ?loc:(if loc = None then f.t_loc else loc) attrs f
Andrei Paskevich's avatar
Andrei Paskevich committed
162

163 164 165 166 167 168
(* propositional connectives with limited simplification *)

let sp_implies sp wp = match sp.t_node, wp.t_node with
  | Ttrue, _ | _, Ttrue -> wp
  | _, _ -> t_implies sp wp

169
let sp_or sp1 sp2 = match sp1.t_node, sp2.t_node with
170 171
  | Ttrue, _ | _, Tfalse -> sp1
  | _, Ttrue | Tfalse, _ -> sp2
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
172
  | _, _ -> add_case (t_or sp1 sp2)
173

174
let sp_and sp1 sp2 = match sp1.t_node, sp2.t_node with
175 176 177 178
  | Ttrue, _ | _, Tfalse -> sp2
  | _, Ttrue | Tfalse, _ -> sp1
  | _, _ -> t_and sp1 sp2

Andrei Paskevich's avatar
Andrei Paskevich committed
179
(* sp_or adds "case_split", so we avoid using it here *)
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
180
let sp_if c sp1 sp2 = match c.t_node, sp1.t_node, sp2.t_node with
Andrei Paskevich's avatar
Andrei Paskevich committed
181 182
  | Ttrue, _, _  | _, Ttrue,  Ttrue  -> sp1
  | Tfalse, _, _ | _, Tfalse, Tfalse -> sp2
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
183
  | _, _, Tfalse -> sp_and c sp1
Andrei Paskevich's avatar
Andrei Paskevich committed
184 185 186
  | _, Tfalse, _ -> sp_and (t_not_simp c) sp2
  | _, Ttrue, _  -> t_or c sp2
  | _, _, Ttrue  -> t_or (t_not_simp c) sp1
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
187 188 189 190 191 192 193
  | _, _, _ -> add_case (t_if c sp1 sp2)

let sp_case t bl =
  let isfalse b = match t_open_branch b with
    | _, { t_node = Tfalse } -> true | _ -> false in
  if List.for_all isfalse bl then t_false else add_case (t_case t bl)

Andrei Paskevich's avatar
Andrei Paskevich committed
194
let can_simp wp = match wp.t_node with
Andrei Paskevich's avatar
Andrei Paskevich committed
195
  | Ttrue -> not (Sattr.mem annot_attr wp.t_attrs)
Andrei Paskevich's avatar
Andrei Paskevich committed
196
  | _ -> false
197 198 199 200 201 202

let wp_and wp1 wp2 = match wp1.t_node, wp2.t_node with
  | (Ttrue, _ | _, Tfalse) when can_simp wp1 -> wp2
  | (_, Ttrue | Tfalse, _) when can_simp wp2 -> wp1
  | _, _ -> t_and wp1 wp2

203 204 205 206 207
let wp_and_asym wp1 wp2 = match wp1.t_node, wp2.t_node with
  | (Ttrue, _ | _, Tfalse) when can_simp wp1 -> wp2
  | (_, Ttrue | Tfalse, _) when can_simp wp2 -> wp1
  | _, _ -> t_and_asym wp1 wp2

Andrei Paskevich's avatar
Andrei Paskevich committed
208
let wp_if c wp1 wp2 = match c.t_node, wp1.t_node, wp2.t_node with
209 210
  | Ttrue, _, _  when can_simp wp2 -> wp1
  | Tfalse, _, _ when can_simp wp1 -> wp2
211
  | _, _, Ttrue  when can_simp wp2 -> sp_implies c wp1
Andrei Paskevich's avatar
Andrei Paskevich committed
212
  | _, Ttrue, _  when can_simp wp1 -> sp_implies (t_not_simp c) wp2
213 214
  | _, _, _ -> t_if c wp1 wp2

Andrei Paskevich's avatar
Andrei Paskevich committed
215 216 217 218
let wp_case t bl =
  let check b = can_simp (snd (t_open_branch b)) in
  if List.for_all check bl then t_true else t_case t bl

219
let wp_forall vl wp = t_forall_close_simp vl [] wp
220
let sp_exists vl sp = t_exists_close_simp vl [] sp
221

Andrei Paskevich's avatar
Andrei Paskevich committed
222 223 224 225 226 227 228 229
let wp_let v t wp =
  if pv_is_unit v then t_subst_single v.pv_vs t_void wp
                  else t_let_close_simp v.pv_vs t wp

let sp_let v t sp rd =
  if pv_is_unit v then t_subst_single v.pv_vs t_void sp else
  if Spv.mem v rd then sp_and (t_equ (t_var v.pv_vs) t) sp else
  t_let_close_simp v.pv_vs t sp
230

231 232 233 234 235 236 237 238 239 240 241
(* affected program variables *)

let ity_affected wr ity =
  Util.any ity_rch_fold (Mreg.contains wr) ity

let pv_affected wr v = ity_affected wr v.pv_ity

let pvs_affected wr pvs =
  if Mreg.is_empty wr then Spv.empty
  else Spv.filter (pv_affected wr) pvs

242
(* variant decrease preconditions *)
243 244 245

let decrease_alg env loc old_t t =
  let oty = t_type old_t and nty = t_type t in
246
  let quit () = Loc.errorm ?loc "no default order for %a" Pretty.print_ty nty in
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  let ts = match oty with {ty_node = Tyapp (ts,_)} -> ts | _ -> quit () in
  let itd = find_its_defn env.known_map (restore_its ts) in
  let get_cs rs = match rs.rs_logic with RLls cs -> cs | _ -> quit () in
  let csl = List.map get_cs itd.itd_constructors in
  if csl = [] then quit ();
  let sbs = ty_match Mtv.empty (ty_app ts (List.map ty_var ts.ts_args)) oty in
  let add_arg fty acc =
    let fty = ty_inst sbs fty in
    if ty_equal fty nty then
      let vs = create_vsymbol (id_fresh "f") nty in
      pat_var vs, t_or_simp (t_equ (t_var vs) t) acc
    else pat_wild fty, acc in
  let add_cs cs =
    let pl, f = Lists.map_fold_right add_arg cs.ls_args t_false in
    t_close_branch (pat_app cs pl oty) f in
  t_case old_t (List.map add_cs csl)

let decrease_def env loc old_t t =
265 266 267 268
  let ty = t_type t in
  if ty_equal (t_type old_t) ty then
    match ty.ty_node with
    | Tyapp (ts,_) when ts_equal ts ts_int ->
Andrei Paskevich's avatar
Andrei Paskevich committed
269 270
        t_and (ps_app env.ps_int_le [t_nat_const 0; old_t])
              (ps_app env.ps_int_lt [t; old_t])
271
    | Tyapp (ts, _) when is_range_type_def ts.ts_def ->
Andrei Paskevich's avatar
Andrei Paskevich committed
272 273 274
        let ls = int_of_range env ts in
        let proj t = fs_app ls [t] ty_int in
        ps_app env.ps_int_lt [proj t; proj old_t]
275
    | _ ->
Andrei Paskevich's avatar
Andrei Paskevich committed
276
        decrease_alg env loc old_t t
277 278
  else decrease_alg env loc old_t t

Andrei Paskevich's avatar
Andrei Paskevich committed
279
let decrease env loc attrs expl olds news =
280
  if olds = [] && news = [] then t_true else
281
  let rec decr olds news = match olds, news with
282 283
    | (old_t, Some old_r)::olds, (t, Some r)::news when ls_equal old_r r ->
        if t_equal old_t t then decr olds news else
284
        let dt = t_and (ps_app r [t; old_t]) (acc env r old_t) in
285 286 287 288 289
        t_or_simp dt (t_and_simp (t_equ old_t t) (decr olds news))
    | (old_t, None)::olds, (t, None)::news when oty_equal old_t.t_ty t.t_ty ->
        if t_equal old_t t then decr olds news else
        let dt = decrease_def env loc old_t t in
        t_or_simp dt (t_and_simp (t_equ old_t t) (decr olds news))
290 291
    | (old_t, None)::_, (t, None)::_ ->
        decrease_def env loc old_t t
292
    | _::_, [] -> t_true
293
    | _ -> t_false in
Andrei Paskevich's avatar
Andrei Paskevich committed
294
  vc_expl loc attrs expl (decr olds news)
Andrei Paskevich's avatar
Andrei Paskevich committed
295

296 297 298
let old_of_pv {pv_vs = v; pv_ity = ity} =
  create_pvsymbol (id_clone v.vs_name) (ity_purify ity)

Andrei Paskevich's avatar
Andrei Paskevich committed
299 300
let oldify_variant varl =
  let fpv = Mpv.mapi_filter (fun v _ -> (* oldify mutable vars *)
301
    if v.pv_ity.ity_pure then None else Some (old_of_pv v))
Andrei Paskevich's avatar
Andrei Paskevich committed
302
    (List.fold_left (fun s (t,_) -> t_freepvs s t) Spv.empty varl) in
303
  if Mpv.is_empty fpv then Mpv.empty, varl else
304 305
  let o2v = Mpv.fold (fun v o s -> Mpv.add o v s) fpv Mpv.empty in
  let v2o = Mpv.fold (fun v o s ->
Andrei Paskevich's avatar
Andrei Paskevich committed
306
    Mvs.add v.pv_vs (t_var o.pv_vs) s) fpv Mvs.empty in
307 308 309 310 311 312
  o2v, List.map (fun (t,r) -> t_subst v2o t, r) varl

let renew_oldies o2v =
  let renew o v (n2v, o2n) = let n = old_of_pv v in
    Mpv.add n v n2v, Mvs.add o.pv_vs (t_var n.pv_vs) o2n in
  Mpv.fold renew o2v (Mpv.empty, Mvs.empty)
313

314
(* convert user specifications into goals (wp) and premises (sp) *)
Andrei Paskevich's avatar
Andrei Paskevich committed
315

Andrei Paskevich's avatar
Andrei Paskevich committed
316 317
let wp_of_inv loc attrs expl pl =
  t_and_asym_l (List.map (vc_expl loc attrs expl) pl)
Andrei Paskevich's avatar
Andrei Paskevich committed
318

Andrei Paskevich's avatar
Andrei Paskevich committed
319
let wp_of_pre loc attrs pl = wp_of_inv loc attrs expl_pre pl
Andrei Paskevich's avatar
Andrei Paskevich committed
320

321
let wp_of_post expl ity ql =
322
  let v = res_of_post ity ql in let t = t_var v.pv_vs in
Andrei Paskevich's avatar
Andrei Paskevich committed
323
  let make q = vc_expl None Sattr.empty expl (open_post_with t q) in
324
  v, t_and_asym_l (List.map make ql)
Andrei Paskevich's avatar
Andrei Paskevich committed
325

Andrei Paskevich's avatar
Andrei Paskevich committed
326
let push_stop loc attrs expl f =
327
  let rec push f = match f.t_node with
328
    | Tbinop (Tand,g,h)
Andrei Paskevich's avatar
Andrei Paskevich committed
329 330 331
      when not (Sattr.mem annot_attr f.t_attrs) ->
        t_attr_copy f (t_and (push g) (push h))
    | _ -> vc_expl loc attrs expl f in
332
  push f
Andrei Paskevich's avatar
Andrei Paskevich committed
333

Andrei Paskevich's avatar
Andrei Paskevich committed
334 335
let sp_of_inv loc attrs expl pl =
  t_and_l (List.map (push_stop loc attrs expl) pl)
336

Andrei Paskevich's avatar
Andrei Paskevich committed
337
let sp_of_pre pl = sp_of_inv None Sattr.empty expl_pre pl
338

Andrei Paskevich's avatar
Andrei Paskevich committed
339 340
let sp_of_post loc attrs expl v ql = let t = t_var v.pv_vs in
  let push q = push_stop loc attrs expl (open_post_with t q) in
341 342
  t_and_l (List.map push ql)

343 344 345 346
(* definitions of local let-functions are inserted in the VC
   as premises for the subsequent code (in the same way as
   definitions of top-level let-functions are translated to
   logical definitions in Pdecl.create_let_decl) *)
347 348
let cty_enrich_post c = match c with
  | {c_node = Cfun e; c_cty = cty} ->
349 350
      let {pv_vs = u} = res_of_cty cty in
      let prop = ty_equal u.vs_ty ty_bool in
351
      begin match term_of_expr ~prop e with
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
      | Some f ->
          let f = match f.t_node with
            | Tapp (ps, [t; {t_node = Tapp (fs,[])}])
              when ls_equal ps ps_equ
                && ls_equal fs fs_bool_true -> t
            | _ -> f in
          let q = match f.t_ty with
            | None -> t_iff (t_equ (t_var u) t_bool_true) f
            | Some _ -> t_equ (t_var u) f in
          cty_add_post cty [create_post u q]
      | None when cty.cty_post = [] ->
          begin match post_of_expr (t_var u) e with
          | Some f -> cty_add_post cty [create_post u f]
          | None -> cty end
      | None -> cty end
367 368
  | _ -> c.c_cty

369
(* k-expressions: simplified code *)
370

Andrei Paskevich's avatar
Andrei Paskevich committed
371
type ktag = WP | SP | Out of bool Mint.t | Push of bool | Off of attribute
372 373

type kode =
374 375 376 377
  | Kseq   of kode * int * kode           (* 0: sequence, N: try-with *)
  | Kpar   of kode * kode                 (* non-deterministic choice *)
  | Kif    of pvsymbol * kode * kode          (* deterministic choice *)
  | Kcase  of pvsymbol * (pattern * kode) list    (* pattern matching *)
378 379
  | Khavoc of pvsymbol option Mpv.t Mreg.t *
              Loc.position option           (* writes and assignments *)
380 381 382 383 384 385 386 387 388 389 390 391 392
  | Klet   of pvsymbol * term * term         (* let v = t such that f *)
  | Kval   of pvsymbol list * term        (* let vl = any such that f *)
  | Kcut   of term                        (* assert: check and assume *)
  | Kstop  of term                        (* check and halt execution *)
  | Kcont  of int                                (* 0: skip, N: raise *)
  | Kaxiom of kode                  (* axiom-functions: assume the VC *)
  | Ktag   of ktag * kode          (* switch VCgen or mark to push up *)

(* kode requires, and expr provides, the following invariants:
   - a used variable must be defined by Klet or declared by Kval
     on every codepath leading to its use, and only once
   - in Klet(v,t,_), variable v does not occur in term t
   - every visible variable is a pvsymbol *)
393 394

let rec k_print fmt k = match k with
Andrei Paskevich's avatar
Andrei Paskevich committed
395
  | Kseq (k1 ,0, k2) -> Format.fprintf fmt
396
      "@[%a;@\n%a@]" k_print k1 k_print k2
Andrei Paskevich's avatar
Andrei Paskevich committed
397
  | Kseq (k1, i, k2) -> Format.fprintf fmt
398
      "@[TRY %a@\n%d : %a@]" k_print k1 i k_print k2
Andrei Paskevich's avatar
Andrei Paskevich committed
399
  | Kpar (Kstop f, k2) -> Format.fprintf fmt
400
      "@[@[<hov 4>CHECK %a@];@\n%a@]" Pretty.print_term f k_print k2
Andrei Paskevich's avatar
Andrei Paskevich committed
401
  | Kpar (k1, k2) -> Format.fprintf fmt
402 403 404 405 406 407 408
      "@[[ @[%a@]@\n| @[%a@] ]@]" k_print k1 k_print k2
  | Kif (v, k1, k2) -> Format.fprintf fmt
      "@[IF %a@\nTHEN %a@\nELSE %a@]"
        Ity.print_pv v k_print k1 k_print k2
  | Kcase (v, bl) ->
      let branch fmt (p,k) = Format.fprintf fmt
        "@[<hov 4>| %a ->@ %a@]" Pretty.print_pat p k_print k in
Andrei Paskevich's avatar
Andrei Paskevich committed
409
      Format.fprintf fmt "@[CASE %a\n@[%a@]@]"
410
        Ity.print_pv v (Pp.print_list Pp.newline branch) bl
411
  | Khavoc _ -> Format.fprintf fmt "HAVOC" (* TODO *)
Andrei Paskevich's avatar
Andrei Paskevich committed
412
  | Klet (v, t, {t_node = Ttrue}) -> Format.fprintf fmt
413 414
      "@[<hov 4>LET %a = %a@]" Ity.print_pv v Pretty.print_term t
  | Klet (v,t,f) -> Format.fprintf fmt
Andrei Paskevich's avatar
Andrei Paskevich committed
415
      "@[<hov 4>LET %a = %a WITH@ %a@]" Ity.print_pv v
416 417 418 419
        Pretty.print_term t Pretty.print_term f
  | Kval (vl,{t_node = Ttrue}) -> Format.fprintf fmt
      "@[<hov 4>VAL %a@]" (Pp.print_list Pp.space Ity.print_pv) vl
  | Kval (vl,f) -> Format.fprintf fmt
Andrei Paskevich's avatar
Andrei Paskevich committed
420
      "@[<hov 4>VAL %a WITH@ %a@]"
421 422 423 424
        (Pp.print_list Pp.space Ity.print_pv) vl Pretty.print_term f
  | Kcut f -> Format.fprintf fmt
      "@[<hov 4>ASSERT %a@]" Pretty.print_term f
  | Kstop f -> Format.fprintf fmt
Andrei Paskevich's avatar
Andrei Paskevich committed
425
      "@[<hov 4>STOP %a@]" Pretty.print_term f
426 427 428 429 430 431 432 433 434
  | Kcont 0 -> Format.fprintf fmt "SKIP"
  | Kcont i -> Format.fprintf fmt "RAISE %d" i
  | Kaxiom k -> Format.fprintf fmt "@[<hov 4>AXIOM %a@]" k_print k
  | Ktag (WP, k) -> Format.fprintf fmt "@[<hov 4>WP %a@]" k_print k
  | Ktag (SP, k) -> Format.fprintf fmt "@[<hov 4>SP %a@]" k_print k
  | Ktag (Out out, k) -> Format.fprintf fmt "@[<hov 4>OUT %a %a@]"
      (Pp.print_list Pp.space Pp.int) (Mint.keys out) k_print k
  | Ktag (Push cl, k) -> Format.fprintf fmt "@[<hov 4>PUSH %s %a@]"
      (if cl then "CLOSED" else "OPEN") k_print k
Andrei Paskevich's avatar
Andrei Paskevich committed
435 436
  | Ktag (Off attr, k) -> Format.fprintf fmt "@[<hov 4>OFF %s %a@]"
      attr.attr_string k_print k
437

438
(* check if a pure k-expression can be converted to a term.
Guillaume Melquiond's avatar
Guillaume Melquiond committed
439
   We need this for simple conjunctions, disjunctions, and
440 441
   pattern-matching exprs, to avoid considering each branch
   separately; also to have a single substitutable term. *)
442 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
let term_of_kode res k =
  let rec get_stack st k = match k with
    | Klet (v, t, f) when pv_equal v res -> st, Some (t, f), 0, Kcont 0
    | Klet (v, t, _) -> (v, Some t) :: st, None, 0, k
    | Kval (vl, _) ->
        let none v = if pv_is_unit v then Some t_void else None in
        List.fold_left (fun st v -> (v, none v) :: st) st vl, None, 0, k
    | Kcut _ | Kaxiom _ -> st, None, 0, k
    | Kcont i -> st, None, i, k
    | Kseq (k1, i, k2) ->
        let st, d, j, k1 = get_stack st k1 in
        if i <> j then st, d, j, Kseq (k1, i, k2) else
        if d <> None then raise Exit else
        let st, d, j, k2 = get_stack st k2 in
        st, d, j, Kseq (k1, i, k2)
    | Ktag (tag, k2) ->
        let st, d, i, k2 = get_stack st k2 in st, d, i, Ktag (tag, k2)
    | Kpar ((Kstop _) as k1, k2) ->
        let st, d, i, k2 = get_stack st k2 in st, d, i, Kpar (k1, k2)
    | Kpar _ | Kif _ | Kcase _ | Khavoc _ | Kstop _ -> raise Exit in
  let st, d, i, k = get_stack [] k in
  if i <> 0 then raise Exit else
  match d with
  | Some (t, f) ->
      let unwind t ({pv_vs = v}, d) = match d with
        | Some d -> t_let_close_simp v d t
        | None when t_v_occurs v t > 0 -> raise Exit
        | None -> t in
      let t = List.fold_left unwind t st in
      let f = if t_closed f then f else
              List.fold_left unwind f st in
      t, f, k
  | None -> raise Exit

476 477
(* stage 1: expr -> kode *)

478 479 480 481
let k_unit res = Kval ([res], t_true)

let bind_oldies o2v k = Mpv.fold (fun o v k ->
  Kseq (Klet (o, t_var v.pv_vs, t_true), 0, k)) o2v k
482

483
let k_havoc loc eff k =
484 485
  if Sreg.is_empty eff.eff_covers then k else
  let conv wr = Mpv.map (fun () -> None) wr in
486
  Kseq (Khavoc (Mreg.map conv eff.eff_writes, loc), 0, k)
487

488 489 490
(* missing exceptional postconditions are set to True,
   unless we skip them altogether and let the exception
   escape into the outer code (only for abstract blocks) *)
491
let complete_xpost cty {eff_raises = xss} skip =
492 493
  Mxs.set_union (Mxs.set_inter cty.cty_xpost xss)
    (Mxs.map (fun () -> []) (Mxs.set_diff xss skip))
494

Andrei Paskevich's avatar
Andrei Paskevich committed
495 496
let wp_solder expl wp =
  if can_simp wp then wp else
Andrei Paskevich's avatar
Andrei Paskevich committed
497 498
  let wp = t_attr_add stop_split wp in
  if attrs_has_expl wp.t_attrs then wp else t_attr_add expl wp
Andrei Paskevich's avatar
Andrei Paskevich committed
499

500
let rec explain_inv loc f = match f.t_node with
Andrei Paskevich's avatar
Andrei Paskevich committed
501 502
  | Tapp _ -> vc_expl loc Sattr.empty expl_type_inv f
  | _ -> t_map (explain_inv loc) (t_attr_set ?loc Sattr.empty f)
503

504
let inv_of_pvs, inv_of_loop =
505 506 507
  let a = create_tvsymbol (id_fresh "a") in
  let ps_dummy = create_psymbol (id_fresh "dummy") [ty_var a] in
  let mk_dummy v = ps_app ps_dummy [t_var v.pv_vs] in
508 509 510 511 512 513 514 515
  let add_varl fl (t,_) = ps_app ps_dummy [t] :: fl in
  (fun {known_map = kn} loc pvs ->
    let fl = List.map mk_dummy (Spv.elements pvs) in
    List.map (explain_inv loc) (Typeinv.inspect kn fl)),
  (fun {known_map = kn} loc fl varl ->
    let fl = List.fold_left add_varl fl varl in
    List.map (explain_inv loc) (Typeinv.inspect kn fl))

516 517 518
let assume_inv inv k = Kseq (Kval ([], inv), 0, k)
let assert_inv inv k = Kpar (Kstop inv, assume_inv inv k)

519 520 521 522
let inv_of_pure {known_map = kn} loc fl k =
  let add f k = assert_inv (explain_inv loc f) k in
  List.fold_right add (Typeinv.inspect kn fl) k

523 524 525 526 527
(* translate the expression [e] into a k-expression:
   [lps] stores the variants of outer recursive functions
   [res] names the result of the normal execution of [e]
   [xmap] maps every raised exception to a pair [i,xres]:
   - [i] is a positive int assigned at the catching site
528 529
   - [xres] names the value carried by the exception
   [case_xmap] is used for match-with-exceptions *)
530
let rec k_expr env lps e res xmap =
531
  let loc = e.e_loc and eff = e.e_effect in
Andrei Paskevich's avatar
Andrei Paskevich committed
532 533
  let attrs = Sattr.diff e.e_attrs vc_attrs in
  let t_tag t = t_attr_set ?loc attrs t in
534 535
  let var_or_proxy_case xmap e k =
    match e.e_node with
536 537
    | Evar v -> k v
    | _ -> let v = proxy_of_expr e in
538 539
           Kseq (k_expr env lps e v xmap, 0, k v) in
  let var_or_proxy = var_or_proxy_case xmap in
540
  let check_divergence k =
541
    if diverges eff.eff_oneway && not env.divergent then begin
542
      if Debug.test_noflag debug_ignore_diverges then
543 544 545 546 547
      Warning.emit ?loc "termination@ of@ this@ expression@ \
        cannot@ be@ proved,@ but@ there@ is@ no@ `diverges'@ \
        clause@ in@ the@ outer@ specification";
      Kpar (Kstop (vc_expl loc attrs expl_divergent t_false), k)
    end else k in
548 549
  let k = match e.e_node with
    | Evar v ->
Andrei Paskevich's avatar
Andrei Paskevich committed
550
        Klet (res, t_tag (t_var v.pv_vs), t_true)
551
    | Econst c ->
Andrei Paskevich's avatar
Andrei Paskevich committed
552
        Klet (res, t_tag (t_const c (ty_of_ity e.e_ity)), t_true)
Andrei Paskevich's avatar
Andrei Paskevich committed
553
    | Eexec ({c_node = Cfun e1; c_cty = {cty_args = []} as cty}, _)
Andrei Paskevich's avatar
Andrei Paskevich committed
554
      when Sattr.mem wb_attr e.e_attrs ->
Andrei Paskevich's avatar
Andrei Paskevich committed
555 556 557
        (* white-box blocks do not hide their contents from the external
           computation. Instead, their pre and post are simply added as
           assertions at the beginning and the end of the expression.
Andrei Paskevich's avatar
Andrei Paskevich committed
558
           All preconditions are thus preserved (as with kp_attr).
Andrei Paskevich's avatar
Andrei Paskevich committed
559 560 561
           White-box blocks do not force type invariants. *)
        let k_of_post expl v ql =
          let make = let t = t_var v.pv_vs in fun q ->
Andrei Paskevich's avatar
Andrei Paskevich committed
562
            vc_expl None attrs expl (open_post_with t q) in
Andrei Paskevich's avatar
Andrei Paskevich committed
563 564 565 566 567
          let sp = t_and_asym_l (List.map make ql) in
          let k = match sp.t_node with
            | Tfalse -> Kstop sp | _ -> Kcut sp in
          inv_of_pure env loc [sp] k in
        (* normal pre- and postcondition *)
Andrei Paskevich's avatar
Andrei Paskevich committed
568
        let pre = wp_of_pre None attrs cty.cty_pre in
Andrei Paskevich's avatar
Andrei Paskevich committed
569 570 571
        let pre = inv_of_pure env loc [pre] (Kcut pre) in
        let post = k_of_post expl_post res cty.cty_post in
        (* handle exceptions that pass through *)
572
        let xs_pass = eff.eff_raises in
Andrei Paskevich's avatar
Andrei Paskevich committed
573 574 575 576 577 578
        let xq_pass = Mxs.set_inter cty.cty_xpost xs_pass in
        let xq_pass = Mxs.inter (fun _ ql (i,v) ->
          let xq = k_of_post expl_xpost v ql in
          Some ((i,v), Kseq (xq, 0, Kcont i))) xq_pass xmap in
        (* each exception raised in e1 but not in e is hidden
           due to an exceptional postcondition False in xpost *)
Andrei Paskevich's avatar
Andrei Paskevich committed
579
        let bot = Kstop (vc_expl loc attrs expl_absurd t_false) in
Andrei Paskevich's avatar
Andrei Paskevich committed
580 581 582 583 584 585 586 587 588 589 590 591 592
        let xs_lost = Sxs.diff e1.e_effect.eff_raises xs_pass in
        let xq_lost = Mxs.set_inter cty.cty_xpost xs_lost in
        let xq_lost = Mxs.mapi (fun xs ql ->
          let v = res_of_post xs.xs_ity ql in
          let xq = k_of_post expl_xpost v ql in
          (new_exn env, v), Kseq (xq, 0, bot)) xq_lost in
        (* complete xmap with new indices, then handle e1 *)
        let xmap = Mxs.set_union (Mxs.map fst xq_lost) xmap in
        let k = Kseq (k_expr env lps e1 res xmap, 0, post) in
        let add_xq _ ((i,_), xq) k = Kseq (k, i, xq) in
        let k = Mxs.fold add_xq xq_lost k in
        let k = Mxs.fold add_xq xq_pass k in
        let k = bind_oldies cty.cty_oldies k in
593 594 595
        (* ignore divergence here if we check it later *)
        let k = if Sattr.mem nt_attr e1.e_attrs
                then check_divergence k else k in
Andrei Paskevich's avatar
Andrei Paskevich committed
596
        if cty.cty_pre = [] then k else Kseq (pre, 0, k)
597 598 599 600
    | Eexec (ce, ({cty_pre = pre; cty_oldies = oldies} as cty)) ->
        (* [ VC(ce) (if ce is a lambda executed in-place)
           | STOP pre
           | HAVOC ; [ ASSUME post | ASSUME xpost ; RAISE ] ] *)
601
        let p, (oldies, sbs) = match pre with
602 603
          (* for recursive calls, compute the 'variant decrease'
             precondition and rename the oldies to avoid clash *)
604 605 606
          | {t_node = Tapp (ls, tl)} :: pl when Mls.mem ls lps ->
              let ovl, rll = Mls.find ls lps in
              let nvl = List.combine tl rll in
Andrei Paskevich's avatar
Andrei Paskevich committed
607 608 609
              let d = decrease env loc attrs expl_variant ovl nvl in
              wp_and d (wp_of_pre loc attrs pl), renew_oldies oldies
          | pl -> wp_of_pre loc attrs pl, (oldies, Mvs.empty) in
610 611 612 613 614 615 616 617
        let trusted = match ce.c_node with
          | (Capp ({rs_logic = RLls ls}, _) | Cpur (ls, _))
            when ce.c_cty.cty_args = [] (* fully applied *) ->
              Typeinv.is_trusted_constructor env.known_map ls ||
              Typeinv.is_trusted_projection env.known_map ls e.e_ity
          | _ -> false in
        let rds = cty.cty_effect.eff_reads in
        let aff = pvs_affected cty.cty_effect.eff_covers rds in
618 619
        let pinv = if trusted then [] else inv_of_pvs env e.e_loc rds in
        let qinv = if trusted then [] else inv_of_pvs env e.e_loc aff in
620
        let k_of_post expl v ql =
Andrei Paskevich's avatar
Andrei Paskevich committed
621
          let sp = sp_of_post loc attrs expl v ql in
622
          let sp = t_subst sbs sp (* rename oldies *) in
623 624
          let rinv = if trusted then [] else
            inv_of_pvs env e.e_loc (Spv.singleton v) in
625
          match term_of_post ~prop:false v.pv_vs sp with
626
          | Some (t, sp) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
627
              Klet (v, t_tag t, List.fold_right sp_and rinv sp)
628
          | None ->  Kval ([v], List.fold_right sp_and rinv sp) in
629
        let k = k_of_post expl_post res cty.cty_post in
630 631 632 633 634
        (* in abstract blocks, exceptions without postconditions
           escape from the block into the outer code. Otherwise,
           every exception in eff_raises is an alternative block
           with the xpost assumed and the exception raised. *)
        let skip = match ce.c_node with
635
          | Cfun _ -> xmap | _ -> Mxs.empty in
636
        let xq = complete_xpost cty eff skip in
637
        let k = Mxs.fold2_inter (fun _ ql (i,v) k ->
638 639
          let xk = k_of_post expl_xpost v ql in
          Kpar(k, Kseq (xk, 0, Kcont i))) xq xmap k in
640
        let k = List.fold_right assume_inv qinv k in
641
        (* oldies and havoc are common for all outcomes *)
642 643 644 645 646
        let k = bind_oldies oldies (k_havoc loc eff k) in
        (* ignore divergence here if we check it later *)
        let k = match ce.c_node with
          | Cfun e when not (Sattr.mem nt_attr e.e_attrs) -> k
          | _ -> check_divergence k in
647
        let k = if pre = [] then k else
Andrei Paskevich's avatar
Andrei Paskevich committed
648
          if Sattr.mem kp_attr e.e_attrs
649 650
            then Kseq (Kcut p, 0, k)
            else Kpar (Kstop p, k) in
651
        let k = List.fold_right assert_inv pinv k in
652 653
        begin match ce.c_node with
          | Cfun e -> Kpar (k_fun env lps ~xmap ce.c_cty e, k)
654 655
          | _ -> k end
    | Eassign asl ->
656
        let cv = eff.eff_covers in
657 658 659
        if Sreg.is_empty cv then k_unit res else
        (* compute the write effect *)
        let add wr (r,f,v) =
660
          let f = fd_of_rs f in
661 662 663 664 665 666
          let r = match r.pv_ity.ity_node with
            | Ityreg r -> r | _ -> assert false in
          Mreg.change (function
            | None   -> Some (Mpv.singleton f v)
            | Some s -> Some (Mpv.add f v s)) r wr in
        let wr = List.fold_left add Mreg.empty asl in
667
        (* we compute the same region bijection as in eff_assign,
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
           except we do not need any consistency checking now *)
        let reg_rexp {reg_its = s; reg_args = tl; reg_regs = rl} wfs =
          let ity_rexp xl t = ity_exp_fold (fun l r -> r :: l) xl t in
          let sbs = its_match_regs s tl rl in
          let mfield xl f = match Mpv.find_opt f wfs with
            | Some v -> ity_rexp xl v.pv_ity
            | None -> ity_rexp xl (ity_full_inst sbs f.pv_ity) in
          List.fold_left mfield [] s.its_mfields in
        let rec stitch t2f rf rt wfs =
          List.fold_left2 link (Mreg.add rt rf t2f)
            (reg_rexp rf Mpv.empty) (reg_rexp rt wfs)
        and link t2f rf rt =
          stitch t2f rf rt (Mreg.find_def Mpv.empty rt wr) in
        (* renaming of regions "dst-to-src" under the surviving regions *)
        let add_write r wfs t2f = stitch t2f r r wfs in
        let t2f = Mreg.fold add_write (Mreg.set_inter wr cv) Mreg.empty in
        (* rearrange the write effect according to the renaming *)
        let add_write r wfs acc =
          try Mreg.add (Mreg.find r t2f) (Mpv.map (fun v -> Some v) wfs) acc
          with Not_found -> acc in
688
        Kseq (Khavoc (Mreg.fold add_write wr Mreg.empty, loc), 0, k_unit res)
689 690 691 692 693 694
    | Elet (LDvar (v, e0), e1) ->
        let k = k_expr env lps e1 res xmap in
        Kseq (k_expr env lps e0 v xmap, 0, k)
    | Elet ((LDsym _| LDrec _) as ld, e1) ->
        let k = k_expr env lps e1 res xmap in
        (* when we havoc the VC of a locally defined function,
695 696 697
           we must take into account every write in the following
           expression and ignore the resets, because the function
           may be executed before the resets. *)
698 699 700 701
        let eff = eff_write e1.e_effect.eff_reads
                            e1.e_effect.eff_writes in
        (* postcondition, as in [Pdecl.create_let_decl] *)
        let add_axiom cty q k = if can_simp q then k else
702
          let p = Kval (cty.cty_args, sp_of_pre cty.cty_pre) in
703
          let ax = Kseq (p, 0, bind_oldies cty.cty_oldies (Kstop q)) in
704
          Kseq (Kaxiom (k_havoc loc eff ax), 0, k) in
705
        let add_axiom cty q k =
706
          let pinv = inv_of_pvs env loc (cty_reads cty) in
707
          List.fold_right assert_inv pinv (add_axiom cty q k) in
708
        let add_rs sm s c (vl,k) = match s.rs_logic with
709 710 711
          | RLls _ -> assert false (* not applicable *)
          | RLnone -> vl, k
          | RLlemma ->
712
              let v = res_of_cty c.c_cty and q = c.c_cty.cty_post in
Andrei Paskevich's avatar
Andrei Paskevich committed
713
              let q = sp_of_post None Sattr.empty expl_post v q in
714 715 716
              let q = if pv_is_unit v
                then t_subst_single v.pv_vs t_void q
                else t_exists_close_simp [v.pv_vs] [] q in
717
              vl, add_axiom c.c_cty q k
718 719 720
          | RLpv v ->
              let c = if Mrs.is_empty sm then c else c_rs_subst sm c in
              let q = cty_exec_post (cty_enrich_post c) in
Andrei Paskevich's avatar
Andrei Paskevich committed
721
              let q = sp_of_post None Sattr.empty expl_post v q in
722
              v::vl, add_axiom c.c_cty q k in
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
        let vl, k = match ld with
          | LDrec rdl ->
              let add_rd sm d = Mrs.add d.rec_rsym d.rec_sym sm in
              let sm = List.fold_left add_rd Mrs.empty rdl in
              let add_rd d dl = add_rs sm d.rec_sym d.rec_fun dl in
              List.fold_right add_rd rdl ([], k)
          | LDsym (s,c) -> add_rs Mrs.empty s c ([], k)
          | LDvar _ -> assert false (* not applicable *) in
        let k = if vl = [] then k else Kseq (Kval (vl, t_true), 0, k) in
        (* precondition *)
        begin match ld with
          | LDrec rdl ->
              let rec k_par = function
                | [k] -> k | [] -> assert false
                | k::kl -> Kpar (k, k_par kl) in
738
              Kpar (k_havoc loc eff (k_par (k_rec env lps rdl)), k)
739
          | LDsym (_, {c_node = Cfun e; c_cty = cty}) ->
740
              Kpar (k_havoc loc eff (k_fun env lps cty e), k)
741 742
          | _ -> k end
    | Eif (e0, e1, e2) ->
743
        (* with both branches pure, switch to SP to avoid splitting *)
744 745 746
        let s = eff_pure e1.e_effect && eff_pure e2.e_effect in
        let k1 = k_expr env lps e1 res xmap in
        let k2 = k_expr env lps e2 res xmap in
747 748
        let kk v =
          if s then try
749 750
            if not (ity_equal e.e_ity ity_bool) ||
              ity_fragile e.e_ity then raise Exit;
751 752
            let t1, f1, k1 = term_of_kode res k1 in
            let t2, f2, k2 = term_of_kode res k2 in
753
            let test = t_equ (t_var v.pv_vs) t_bool_true in
754
            (* with both branches simple, define a resulting term *)
755
            let t = t_if_simp test t1 t2 and f = sp_if test f1 f2 in
756 757 758 759
            Kseq (Ktag (SP, Kif (v, k1, k2)), 0, Klet (res, t, f))
          with Exit -> Ktag (SP, Kif (v, k1, k2))
          else Kif (v, k1, k2) in
        var_or_proxy e0 kk
760
    | Ematch (e0, bl, xl) ->
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
        (* try-with is just another semicolon *)
        let branch xs (vl,e) (xl,xm) =
          let i = new_exn env in
          let xk = k_expr env lps e res xmap in
          (* a single pv for the carried value *)
          let v, xk = match vl with
            | [] -> pv_of_ity "_" ity_unit, xk
            | [v] -> v, xk
            | vl ->
                let v = pv_of_ity "exv" xs.xs_ity in
                let cs = fs_tuple (List.length vl) in
                let pl = List.map (fun v -> pat_var v.pv_vs) vl in
                v, Kcase (v, [pat_app cs pl v.pv_vs.vs_ty, xk]) in
          (i,xk)::xl, Mxs.add xs (i,v) xm in
        let xl, cxmap = Mxs.fold branch xl ([], xmap) in
776
        (* with all branches pure, switch to SP to avoid splitting *)
777 778 779
        let s = List.for_all (fun (_,e) -> eff_pure e.e_effect) bl in
        let branch (pp,e) = pp.pp_pat, k_expr env lps e res xmap in
        let bl = List.map branch bl in
780 781
        let kk v =
          if s then try
782
            if true || ity_fragile e.e_ity then raise Exit;
783 784 785 786 787 788 789
            let add_br (p,k) (bl,tl,fl) =
              let t, f, k = term_of_kode res k in
              let tl = t_close_branch p t :: tl in
              (p,k)::bl, tl, t_close_branch p f :: fl in
            let bl, tl, fl = List.fold_right add_br bl ([],[],[]) in
            (* with all branches simple, define a resulting term *)
            let tv = t_var v.pv_vs in
790
            let t = t_case tv tl and f = sp_case tv fl in
791 792 793
            Kseq (Ktag (SP, Kcase (v, bl)), 0, Klet (res, t, f))
          with Exit -> Ktag (SP, Kcase (v, bl))
          else Kcase (v, bl) in
794 795 796 797 798 799 800 801 802
        let k = match bl with
          | [] ->
              k_expr env lps e0 res cxmap
          | [{pat_node = Pvar v}, k1] ->
              Kseq (k_expr env lps e0 (restore_pv v) cxmap, 0, k1)
          | [p, k1] when Svs.is_empty p.pat_vars ->
              Kseq (k_expr env lps e0 (proxy_of_expr e0) cxmap, 0, k1)
          | _ ->
              var_or_proxy_case cxmap e0 kk in
Guillaume Melquiond's avatar
Guillaume Melquiond committed
803
        (* caught xsymbols are converted to unique integers,
804 805
           so that we can now serialise the "with" clauses
           and avoid capturing the wrong exceptions *)
806 807
        List.fold_left (fun k (i,xk) -> Kseq (k,i,xk)) k xl
    | Eraise (xs, e0) ->
808
        let i, v = Mxs.find xs xmap in
809 810
        Kseq (k_expr env lps e0 v xmap, 0, Kcont i)
    | Eassert (Assert, f) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
811
        let f = vc_expl None attrs expl_assert f in
812 813
        let k = Kseq (Kcut f, 0, k_unit res) in
        inv_of_pure env e.e_loc [f] k
814
    | Eassert (Assume, f) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
815
        let f = vc_expl None attrs expl_assume f in
816 817
        let k = Kval ([res], f) in
        inv_of_pure env e.e_loc [f] k
818
    | Eassert (Check, f) ->
Andrei Paskevich's avatar
Andrei Paskevich committed
819
        let f = vc_expl None attrs expl_check f in
820 821
        let k = Kpar (Kstop f, k_unit res) in
        inv_of_pure env e.e_loc [f] k
822 823
    | Eghost e0
    | Eexn (_,e0) ->
824 825
        k_expr env lps e0 res xmap
    | Epure t ->
Andrei Paskevich's avatar
Andrei Paskevich committed
826 827
        let t = if t.t_ty <> None then t_tag t else
          t_if_simp (t_tag t) t_bool_true t_bool_false in
828 829
        let k = Klet (res, t, t_true) in
        inv_of_pure env e.e_loc [t] k
830
    | Eabsurd ->
Andrei Paskevich's avatar
Andrei Paskevich committed
831
        Kstop (vc_expl loc attrs expl_absurd t_false)
832
    | Ewhile (e0, invl, varl, e1) ->
833 834 835
        (* [ STOP inv
           | HAVOC ; ASSUME inv ; IF e0 THEN e1 ; STOP inv
                                        ELSE SKIP ] *)
Andrei Paskevich's avatar
Andrei Paskevich committed
836 837 838
        let init = wp_of_inv None attrs expl_loop_init invl in
        let prev = sp_of_inv None attrs expl_loop_init invl in
        let keep = wp_of_inv None attrs expl_loop_keep invl in
839
        let oldies, ovarl = oldify_variant varl in
Andrei Paskevich's avatar
Andrei Paskevich committed
840
        let decr = decrease env loc attrs expl_loop_vari ovarl varl in
841
        let keep = wp_and decr keep in
842 843 844 845
        let iinv = inv_of_loop env e.e_loc invl varl in
        let j = List.fold_right assert_inv iinv (Kstop init) in
        let k = List.fold_right assert_inv iinv (Kstop keep) in
        let k = Kseq (k_expr env lps e1 res xmap, 0, k) in
846 847
        let k = var_or_proxy e0 (fun v -> Kif (v, k, k_unit res)) in
        let k = Kseq (Kval ([], prev), 0, bind_oldies oldies k) in
848
        let k = List.fold_right assume_inv iinv k in
849 850
        let k = check_divergence k in
        Kpar (j, k_havoc loc eff k)
851 852 853 854 855
    | Efor (vx, (a, d, b), vi, invl, e1) ->
        let int_of_pv = match vx.pv_vs.vs_ty.ty_node with
          | Tyapp (s,_) when ts_equal s ts_int ->
              fun v -> t_var v.pv_vs
          | Tyapp (s,_) ->
856
              let s = int_of_range env s in
857 858 859 860
              fun v -> fs_app s [t_var v.pv_vs] ty_int
          | Tyvar _ -> assert false (* never *) in
        let a = int_of_pv a and i = t_var vi.pv_vs in
        let b = int_of_pv b and one = t_nat_const 1 in
Andrei Paskevich's avatar
Andrei Paskevich committed
861 862 863
        let init = wp_of_inv None attrs expl_loop_init invl in
        let prev = sp_of_inv None attrs expl_loop_init invl in
        let keep = wp_of_inv None attrs expl_loop_keep invl in
864 865 866 867
        let gt, le, pl = match d with
          | To     -> env.ps_int_gt, env.ps_int_le, env.fs_int_pl
          | DownTo -> env.ps_int_lt, env.ps_int_ge, env.fs_int_mn in
        let bounds = t_and (ps_app le [a; i]) (ps_app le [i; b]) in
Andrei Paskevich's avatar
Andrei Paskevich committed
868
        let expl_bounds f = vc_expl loc attrs expl_for_bound f in
869 870
        let i_pl_1 = fs_app pl [i; one] ty_int in
        let b_pl_1 = fs_app pl [b; one] ty_int in
871 872 873
        let init = t_subst_single vi.pv_vs a init in
        let keep = t_subst_single vi.pv_vs i_pl_1 keep in
        let last = t_subst_single vi.pv_vs b_pl_1 prev in
874 875 876 877
        let iinv = inv_of_loop env e.e_loc invl [] in
        let j = List.fold_right assert_inv iinv (Kstop init) in
        let k = List.fold_right assert_inv iinv (Kstop keep) in
        let k = Kseq (k_expr env lps e1 res xmap, 0, k) in
878 879 880 881 882 883 884
        let k =
          if pv_equal vx vi then
            Kseq (Kval ([vx], sp_and bounds prev), 0, k)
          else
            Kseq (Kval ([vx], t_true), 0,
            Kseq (Klet (vi, int_of_pv vx, sp_and bounds prev), 0, k))
        in
885
        let k = Kpar (k, Kval ([res], last)) in
886
        let k = List.fold_right assume_inv iinv k in
887 888
        let k = Kpar (j, k_havoc loc eff k) in
        let k = check_divergence k in
Andrei Paskevich's avatar
Andrei Paskevich committed
889 890 891 892 893 894 895 896
        (* [ ASSUME a <= b+1 ;
             [ STOP inv[a]
             | HAVOC ; [ ASSUME a <= v <= b /\ inv[v] ; e1 ; STOP inv[v+1]
                       | ASSUME inv[b+1] ] ]
           | ASSUME a > b+1 ] *)
        Kpar (Kseq (Kval ([], expl_bounds (ps_app le [a; b_pl_1])), 0, k),
           Kseq (Kval ([res], expl_bounds (ps_app gt [a; b_pl_1])), 0,
                 Ktag (Off expl_off_bound, Kcont 0)))
897
  in
Andrei Paskevich's avatar
Andrei Paskevich committed
898 899
  if Sattr.mem sp_attr e.e_attrs then Ktag (SP, k) else
  if Sattr.mem wp_attr e.e_attrs then Ktag (WP, k) else k
900

901
and k_fun env lps ?(oldies=Mpv.empty) ?(xmap=Mxs.empty) cty e =
Andrei Paskevich's avatar
Andrei Paskevich committed
902
  (* ASSUME pre ; LET o = arg ; TRY e ; STOP post WITH STOP xpost *)
903 904
  let res, q = wp_of_post expl_post cty.cty_result cty.cty_post in
  let xq = complete_xpost cty e.e_effect xmap in
905
  let xq = Mxs.mapi (fun xs ql ->
906 907
    let v, xq = wp_of_post expl_xpost xs.xs_ity ql in
    (new_exn env, v), xq) xq in
908
  let xmap = Mxs.set_union (Mxs.map fst xq) xmap in
909 910 911 912
  let rds = List.fold_right Spv.add cty.cty_args cty.cty_effect.eff_reads in
  let aff = pvs_affected cty.cty_effect.eff_covers rds in
  let pinv = inv_of_pvs env e.e_loc rds in
  let qinv = inv_of_pvs env e.e_loc aff in
913 914 915 916 917 918 919 920
  let add_qinv v q =
    (* any write in e can potentially produce a broken result.
       In absence of writes, the result cannot be broken, but
       we prefer t