vc.ml 61.9 KB
Newer Older
Andrei Paskevich's avatar
Andrei Paskevich committed
1 2 3
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
Andrei Paskevich's avatar
Andrei Paskevich committed
4
(*  Copyright 2010-2016   --   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.                           *)
(*                                                                  *)
(********************************************************************)

12
open Stdlib
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 *)

Andrei Paskevich's avatar
Andrei Paskevich committed
23
let debug = 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."

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

Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
35
let case_split = Ident.create_label "case_split"
Andrei Paskevich's avatar
Andrei Paskevich committed
36
let add_case t = t_label_add case_split t
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
37

Andrei Paskevich's avatar
Andrei Paskevich committed
38 39
let clone_vs v = create_vsymbol (id_clone v.vs_name) v.vs_ty
let clone_pv v = clone_vs v.pv_vs
Andrei Paskevich's avatar
Andrei Paskevich committed
40

41
let pv_is_unit v = ity_equal v.pv_ity ity_unit
42

43 44 45 46 47 48 49
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
50

Andrei Paskevich's avatar
Andrei Paskevich committed
51 52 53
let proxy_of_expr =
  let label = Slab.singleton proxy_label in fun e ->
  let id = id_fresh ?loc:e.e_loc ~label "o" in
54
  create_pvsymbol id e.e_ity
55

56 57
let sp_label = Ident.create_label "vc:sp"
let wp_label = Ident.create_label "vc:wp"
Andrei Paskevich's avatar
Andrei Paskevich committed
58
let wb_label = Ident.create_label "vc:white_box"
59
let kp_label = Ident.create_label "vc:keep_precondition"
60

Andrei Paskevich's avatar
Andrei Paskevich committed
61 62
let vc_labels = Slab.add kp_label (Slab.add wb_label
  (Slab.add sp_label (Slab.add wp_label Slab.empty)))
63

64 65 66 67
(* VCgen environment *)

type vc_env = {
  known_map : Pdecl.known_map;
68
  ts_ranges : lsymbol Mts.t;
69 70 71 72 73 74
  ps_int_le : lsymbol;
  ps_int_ge : lsymbol;
  ps_int_lt : lsymbol;
  ps_int_gt : lsymbol;
  fs_int_pl : lsymbol;
  fs_int_mn : lsymbol;
75
  exn_count : int ref;
76 77
}

78
let mk_env {Theory.th_export = ns} kn tuc = {
79
  known_map = kn;
80
  ts_ranges = tuc.Theory.uc_ranges;
81 82 83 84 85 86
  ps_int_le = Theory.ns_find_ls ns ["infix <="];
  ps_int_ge = Theory.ns_find_ls ns ["infix >="];
  ps_int_lt = Theory.ns_find_ls ns ["infix <"];
  ps_int_gt = Theory.ns_find_ls ns ["infix >"];
  fs_int_pl = Theory.ns_find_ls ns ["infix +"];
  fs_int_mn = Theory.ns_find_ls ns ["infix -"];
87
  exn_count = ref 0;
88
}
Andrei Paskevich's avatar
Andrei Paskevich committed
89

90 91 92
(* every exception-catching clause is represented by
   a unique integer, so that we can move code inside
   try-with expressions without capturing exceptions *)
93 94 95 96 97
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. *)
98
let mk_env env kn tuc = mk_env (Env.read_theory env ["int"] "Int") kn tuc
Andrei Paskevich's avatar
Andrei Paskevich committed
99

100
(* explanation labels *)
Andrei Paskevich's avatar
Andrei Paskevich committed
101

Andrei Paskevich's avatar
Andrei Paskevich committed
102
let expl_pre       = Ident.create_label "expl:precondition"
103 104
let expl_post      = Ident.create_label "expl:postcondition"
let expl_xpost     = Ident.create_label "expl:exceptional postcondition"
105 106 107
let expl_assume    = Ident.create_label "expl:assumption"
let expl_assert    = Ident.create_label "expl:assertion"
let expl_check     = Ident.create_label "expl:check"
108
let expl_lemma     = Ident.create_label "expl:lemma"
109
let expl_absurd    = Ident.create_label "expl:unreachable point"
110
let expl_for_bound = Ident.create_label "expl:loop bounds"
Andrei Paskevich's avatar
Andrei Paskevich committed
111
let expl_off_bound = Ident.create_label "expl:out of loop bounds"
Andrei Paskevich's avatar
Andrei Paskevich committed
112 113 114
let expl_loop_init = Ident.create_label "expl:loop invariant init"
let expl_loop_keep = Ident.create_label "expl:loop invariant preservation"
let expl_loop_vari = Ident.create_label "expl:loop variant decrease"
115
let expl_variant   = Ident.create_label "expl:variant decrease"
116
let expl_type_inv  = Ident.create_label "expl:type invariant"
Andrei Paskevich's avatar
Andrei Paskevich committed
117

118 119
let lab_has_expl lab =
  Slab.exists (fun l -> Strings.has_prefix "expl:" l.lab_string) lab
Andrei Paskevich's avatar
Andrei Paskevich committed
120

121 122
let annot_labels = Slab.add stop_split (Slab.singleton annot_label)

123
let vc_expl loc lab expl f =
124
  let lab = Slab.union annot_labels (Slab.union lab f.t_label) in
125 126
  let lab = if lab_has_expl lab then lab else Slab.add expl lab in
  t_label ?loc:(if loc = None then f.t_loc else loc) lab f
Andrei Paskevich's avatar
Andrei Paskevich committed
127

128 129 130 131 132 133
(* 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

134
let sp_or sp1 sp2 = match sp1.t_node, sp2.t_node with
135 136
  | Ttrue, _ | _, Tfalse -> sp1
  | _, Ttrue | Tfalse, _ -> sp2
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
137
  | _, _ -> add_case (t_or sp1 sp2)
138

139
let sp_and sp1 sp2 = match sp1.t_node, sp2.t_node with
140 141 142 143
  | Ttrue, _ | _, Tfalse -> sp2
  | _, Ttrue | Tfalse, _ -> sp1
  | _, _ -> t_and sp1 sp2

Andrei Paskevich's avatar
Andrei Paskevich committed
144
(* sp_or adds "case_split", so we avoid using it here *)
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
145
let sp_if c sp1 sp2 = match c.t_node, sp1.t_node, sp2.t_node with
Andrei Paskevich's avatar
Andrei Paskevich committed
146 147
  | Ttrue, _, _  | _, Ttrue,  Ttrue  -> sp1
  | Tfalse, _, _ | _, Tfalse, Tfalse -> sp2
Jean-Christophe Filliâtre's avatar
Jean-Christophe Filliâtre committed
148
  | _, _, Tfalse -> sp_and c sp1
Andrei Paskevich's avatar
Andrei Paskevich committed
149 150 151
  | _, 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
152 153 154 155 156 157 158
  | _, _, _ -> 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
159
let can_simp wp = match wp.t_node with
160
  | Ttrue -> not (Slab.mem annot_label wp.t_label)
Andrei Paskevich's avatar
Andrei Paskevich committed
161
  | _ -> false
162 163 164 165 166 167

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

168 169 170 171 172
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
173
let wp_if c wp1 wp2 = match c.t_node, wp1.t_node, wp2.t_node with
174 175
  | Ttrue, _, _  when can_simp wp2 -> wp1
  | Tfalse, _, _ when can_simp wp1 -> wp2
176
  | _, _, Ttrue  when can_simp wp2 -> sp_implies c wp1
Andrei Paskevich's avatar
Andrei Paskevich committed
177
  | _, Ttrue, _  when can_simp wp1 -> sp_implies (t_not_simp c) wp2
178 179
  | _, _, _ -> t_if c wp1 wp2

Andrei Paskevich's avatar
Andrei Paskevich committed
180 181 182 183
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

184
let wp_forall vl wp = t_forall_close_simp vl [] wp
185
let sp_exists vl sp = t_exists_close_simp vl [] sp
186

Andrei Paskevich's avatar
Andrei Paskevich committed
187 188 189 190 191 192 193 194
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
195

196 197 198 199 200 201 202 203 204 205 206
(* 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

207
(* variant decrease preconditions *)
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

let decrease_alg env loc old_t t =
  let oty = t_type old_t and nty = t_type t in
  let quit () = Loc.errorm ?loc "no default order for %a" Pretty.print_term t in
  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 =
  if ty_equal (t_type old_t) ty_int && ty_equal (t_type t) ty_int
  then t_and (ps_app env.ps_int_le [t_nat_const 0; old_t])
             (ps_app env.ps_int_lt [t; old_t])
  else decrease_alg env loc old_t t

235
let decrease env loc lab expl olds news =
236 237 238 239 240 241 242 243 244 245 246 247
  let rec decr olds news = match olds, news with
    | (old_t, Some old_r)::olds, (t, Some r)::news
      when oty_equal old_t.t_ty t.t_ty && ls_equal old_r r ->
        let dt = ps_app r [t; old_t] in
        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 ->
        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))
    | (old_t, None)::_, (t, None)::_ ->
        decrease_def env loc old_t t
    | _ -> t_false in
248
  vc_expl loc lab expl (decr olds news)
Andrei Paskevich's avatar
Andrei Paskevich committed
249

250 251 252
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
253 254 255 256
let oldify_variant varl =
  let fpv = Mpv.mapi_filter (fun v _ -> (* oldify mutable vars *)
    if ity_immutable v.pv_ity then None else Some (old_of_pv v))
    (List.fold_left (fun s (t,_) -> t_freepvs s t) Spv.empty varl) in
257
  if Mpv.is_empty fpv then Mpv.empty, varl else
258 259
  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
260
    Mvs.add v.pv_vs (t_var o.pv_vs) s) fpv Mvs.empty in
261 262 263 264 265 266
  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)
267

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

270
let wp_of_inv loc lab expl pl =
271
  t_and_asym_l (List.map (vc_expl loc lab expl) pl)
Andrei Paskevich's avatar
Andrei Paskevich committed
272

273
let wp_of_pre loc lab pl = wp_of_inv loc lab expl_pre pl
Andrei Paskevich's avatar
Andrei Paskevich committed
274

275
let wp_of_post expl ity ql =
276
  let v = res_of_post ity ql in let t = t_var v.pv_vs in
277
  let make q = vc_expl None Slab.empty expl (open_post_with t q) in
278
  v, t_and_asym_l (List.map make ql)
Andrei Paskevich's avatar
Andrei Paskevich committed
279

280 281
let push_stop loc lab expl f =
  let rec push f = match f.t_node with
282 283
    | Tbinop (Tand,g,h)
      when not (Slab.mem annot_label f.t_label) ->
284 285 286
        t_label_copy f (t_and (push g) (push h))
    | _ -> vc_expl loc lab expl f in
  push f
Andrei Paskevich's avatar
Andrei Paskevich committed
287

288 289 290
let sp_of_inv loc lab expl pl =
  t_and_l (List.map (push_stop loc lab expl) pl)

291
let sp_of_pre pl = sp_of_inv None Slab.empty expl_pre pl
292 293 294 295 296

let sp_of_post loc lab expl v ql = let t = t_var v.pv_vs in
  let push q = push_stop loc lab expl (open_post_with t q) in
  t_and_l (List.map push ql)

297 298 299 300
(* 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) *)
301 302
let cty_enrich_post c = match c with
  | {c_node = Cfun e; c_cty = cty} ->
303 304
      let {pv_vs = u} = res_of_cty cty in
      let prop = ty_equal u.vs_ty ty_bool in
305
      begin match term_of_expr ~prop e with
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
      | 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
321 322
  | _ -> c.c_cty

323
(* k-expressions: simplified code *)
324

Andrei Paskevich's avatar
Andrei Paskevich committed
325
type ktag = WP | SP | Out of bool Mint.t | Push of bool | Off of label
326 327

type kode =
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  | 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 *)
  | Khavoc of pvsymbol option Mpv.t Mreg.t  (* writes and assignments *)
  | 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 *)
346 347

let rec k_print fmt k = match k with
Andrei Paskevich's avatar
Andrei Paskevich committed
348
  | Kseq (k1 ,0, k2) -> Format.fprintf fmt
349
      "@[%a;@\n%a@]" k_print k1 k_print k2
Andrei Paskevich's avatar
Andrei Paskevich committed
350
  | Kseq (k1, i, k2) -> Format.fprintf fmt
351
      "@[TRY %a@\n%d : %a@]" k_print k1 i k_print k2
Andrei Paskevich's avatar
Andrei Paskevich committed
352
  | Kpar (Kstop f, k2) -> Format.fprintf fmt
353
      "@[@[<hov 4>CHECK %a@];@\n%a@]" Pretty.print_term f k_print k2
Andrei Paskevich's avatar
Andrei Paskevich committed
354
  | Kpar (k1, k2) -> Format.fprintf fmt
355 356 357 358 359 360 361
      "@[[ @[%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
362
      Format.fprintf fmt "@[CASE %a\n@[%a@]@]"
363
        Ity.print_pv v (Pp.print_list Pp.newline branch) bl
Andrei Paskevich's avatar
Andrei Paskevich committed
364 365
  | Khavoc _wr -> Format.fprintf fmt "HAVOC" (* TODO *)
  | Klet (v, t, {t_node = Ttrue}) -> Format.fprintf fmt
366 367
      "@[<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
368
      "@[<hov 4>LET %a = %a WITH@ %a@]" Ity.print_pv v
369 370 371 372
        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
373
      "@[<hov 4>VAL %a WITH@ %a@]"
374 375 376 377
        (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
378
      "@[<hov 4>STOP %a@]" Pretty.print_term f
379 380 381 382 383 384 385 386 387
  | 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
388 389
  | Ktag (Off lab, k) -> Format.fprintf fmt "@[<hov 4>OFF %s %a@]"
      lab.lab_string k_print k
390

391 392 393 394
(* check if a pure k-expression can be converted to a term.
   We need this for simple conjuctions, disjuctions, and
   pattern-matching exprs, to avoid considering each branch
   separately; also to have a single substitutable term. *)
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
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

429 430
(* stage 1: expr -> kode *)

431 432 433 434
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
435 436 437 438 439 440

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

441 442 443
(* 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) *)
444
let complete_xpost cty {eff_raises = xss} skip =
445 446
  Mxs.set_union (Mxs.set_inter cty.cty_xpost xss)
    (Mxs.map (fun () -> []) (Mxs.set_diff xss skip))
447

Andrei Paskevich's avatar
Andrei Paskevich committed
448 449 450 451 452
let wp_solder expl wp =
  if can_simp wp then wp else
  let wp = t_label_add stop_split wp in
  if lab_has_expl wp.t_label then wp else t_label_add expl wp

453 454 455 456
let rec explain_inv loc f = match f.t_node with
  | Tapp _ -> vc_expl loc Slab.empty expl_type_inv f
  | _ -> t_map (explain_inv loc) (t_label ?loc Slab.empty f)

457
let inv_of_pvs, inv_of_loop =
458 459 460
  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
461 462 463 464 465 466 467 468
  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))

469 470 471
let assume_inv inv k = Kseq (Kval ([], inv), 0, k)
let assert_inv inv k = Kpar (Kstop inv, assume_inv inv k)

472 473 474 475
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

476 477 478 479 480
(* 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
481 482 483 484
   - [xres] names the value carried by the exception
   [case_xmap] is used for match-with-exceptions *)
let rec k_expr env lps e res ?case_xmap xmap =
  let loc = e.e_loc in
485
  let lab = Slab.diff e.e_label vc_labels in
486
  let t_lab t = t_label ?loc lab t in
487 488
  let var_or_proxy_case xmap e k =
    match e.e_node with
489 490
    | Evar v -> k v
    | _ -> let v = proxy_of_expr e in
491 492
           Kseq (k_expr env lps e v xmap, 0, k v) in
  let var_or_proxy = var_or_proxy_case xmap in
493 494 495
  let k = match e.e_node with
    | Evar v ->
        Klet (res, t_lab (t_var v.pv_vs), t_true)
496 497
    | Econst c ->
        Klet (res, t_lab (t_const c (ty_of_ity e.e_ity)), t_true)
Andrei Paskevich's avatar
Andrei Paskevich committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    | Eexec ({c_node = Cfun e1; c_cty = {cty_args = []} as cty}, _)
      when Slab.mem wb_label e.e_label ->
        (* 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.
           All preconditions are thus preserved (as with kp_label).
           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 ->
            vc_expl None lab expl (open_post_with t q) in
          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 *)
        let pre = wp_of_pre None lab cty.cty_pre in
        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 *)
        let xs_pass = e.e_effect.eff_raises in
        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 *)
        let bot = Kstop (vc_expl loc lab expl_absurd t_false) in
        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
        if cty.cty_pre = [] then k else Kseq (pre, 0, k)
539 540 541 542
    | 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 ] ] *)
543
        let p, (oldies, sbs) = match pre with
544 545
          (* for recursive calls, compute the 'variant decrease'
             precondition and rename the oldies to avoid clash *)
546 547 548 549 550 551
          | {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
              let d = decrease env loc lab expl_variant ovl nvl in
              wp_and d (wp_of_pre loc lab pl), renew_oldies oldies
          | pl -> wp_of_pre loc lab pl, (oldies, Mvs.empty) in
552 553 554 555 556 557 558 559
        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
560 561
        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
562 563 564
        let k_of_post expl v ql =
          let sp = sp_of_post loc lab expl v ql in
          let sp = t_subst sbs sp (* rename oldies *) in
565 566
          let rinv = if trusted then [] else
            inv_of_pvs env e.e_loc (Spv.singleton v) in
567
          match term_of_post ~prop:false v.pv_vs sp with
568 569 570
          | Some (t, sp) ->
              Klet (v, t_lab t, List.fold_right sp_and rinv sp)
          | None ->  Kval ([v], List.fold_right sp_and rinv sp) in
571
        let k = k_of_post expl_post res cty.cty_post in
572 573 574 575 576
        (* 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
577
          | Cfun _ -> xmap | _ -> Mxs.empty in
578
        let xq = complete_xpost cty e.e_effect skip in
579
        let k = Mxs.fold2_inter (fun _ ql (i,v) k ->
580 581
          let xk = k_of_post expl_xpost v ql in
          Kpar(k, Kseq (xk, 0, Kcont i))) xq xmap k in
582
        let k = List.fold_right assume_inv qinv k in
583
        (* oldies and havoc are common for all outcomes *)
584
        let k = bind_oldies oldies (k_havoc e.e_effect k) in
585 586 587 588
        let k = if pre = [] then k else
          if Slab.mem kp_label e.e_label
            then Kseq (Kcut p, 0, k)
            else Kpar (Kstop p, k) in
589
        let k = List.fold_right assert_inv pinv k in
590 591
        begin match ce.c_node with
          | Cfun e -> Kpar (k_fun env lps ~xmap ce.c_cty e, k)
592 593 594 595 596 597
          | _ -> k end
    | Eassign asl ->
        let cv = e.e_effect.eff_covers in
        if Sreg.is_empty cv then k_unit res else
        (* compute the write effect *)
        let add wr (r,f,v) =
598
          let f = fd_of_rs f in
599 600 601 602 603 604
          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
605
        (* we compute the same region bijection as in eff_assign,
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
           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
        Kseq (Khavoc (Mreg.fold add_write wr Mreg.empty), 0, k_unit res)
    | 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)
    | Ecase (e0, [{pp_pat = {pat_node = Pvar v}}, e1]) ->
        let k = k_expr env lps e1 res xmap in
632
        let xmap = Opt.get_def xmap case_xmap in
633 634 635
        Kseq (k_expr env lps e0 (restore_pv v) xmap, 0, k)
    | Ecase (e0, [pp, e1]) when Svs.is_empty pp.pp_pat.pat_vars ->
        let k = k_expr env lps e1 res xmap in
636
        let xmap = Opt.get_def xmap case_xmap in
637 638 639 640
        Kseq (k_expr env lps e0 (proxy_of_expr e0) 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,
641 642 643
           we must take into account every write in the following
           expression and ignore the resets, because the function
           may be executed before the resets. *)
644 645 646 647
        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
648
          let p = Kval (cty.cty_args, sp_of_pre cty.cty_pre) in
649 650
          let ax = Kseq (p, 0, bind_oldies cty.cty_oldies (Kstop q)) in
          Kseq (Kaxiom (k_havoc eff ax), 0, k) in
651 652 653
        let add_axiom cty q k =
          let pinv = inv_of_pvs env e.e_loc (cty_reads cty) in
          List.fold_right assert_inv pinv (add_axiom cty q k) in
654
        let add_rs sm s c (vl,k) = match s.rs_logic with
655 656 657
          | RLls _ -> assert false (* not applicable *)
          | RLnone -> vl, k
          | RLlemma ->
658 659
              let v = res_of_cty c.c_cty and q = c.c_cty.cty_post in
              let q = sp_of_post None Slab.empty expl_post v q in
660 661 662
              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
663
              vl, add_axiom c.c_cty q k
664 665 666 667
          | 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
              let q = sp_of_post None Slab.empty expl_post v q in
668
              v::vl, add_axiom c.c_cty q k in
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
        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
              Kpar (k_havoc eff (k_par (k_rec env lps rdl)), k)
          | LDsym (_, {c_node = Cfun e; c_cty = cty}) ->
              Kpar (k_havoc eff (k_fun env lps cty e), k)
          | _ -> k end
    | Eif (e0, e1, e2) ->
689
        (* with both branches pure, switch to SP to avoid splitting *)
690 691 692
        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
693 694
        let kk v =
          if s then try
695 696
            if not (ity_equal e.e_ity ity_bool) ||
              ity_fragile e.e_ity then raise Exit;
697 698
            let t1, f1, k1 = term_of_kode res k1 in
            let t2, f2, k2 = term_of_kode res k2 in
699
            let test = t_equ (t_var v.pv_vs) t_bool_true in
700
            (* with both branches simple, define a resulting term *)
701
            let t = t_if_simp test t1 t2 and f = sp_if test f1 f2 in
702 703 704 705
            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
706
    | Ecase (e0, bl) ->
707
        (* with all branches pure, switch to SP to avoid splitting *)
708 709 710
        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
711 712
        let kk v =
          if s then try
713
            if true || ity_fragile e.e_ity then raise Exit;
714 715 716 717 718 719 720
            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
721
            let t = t_case tv tl and f = sp_case tv fl in
722 723 724
            Kseq (Ktag (SP, Kcase (v, bl)), 0, Klet (res, t, f))
          with Exit -> Ktag (SP, Kcase (v, bl))
          else Kcase (v, bl) in
725 726 727
        let xmap = Opt.get_def xmap case_xmap in
        var_or_proxy_case xmap e0 kk
    | Etry (e0, case, bl) ->
728
        (* try-with is just another semicolon *)
729 730 731
        let branch xs (vl,e) (xl,xm) =
          let i = new_exn env in
          let xk = k_expr env lps e res xmap in
732
          (* a single pv for the carried value *)
733 734
          let v, xk = match vl with
            | [] -> pv_of_ity "_" ity_unit, xk
735 736
            | [v] -> v, xk
            | vl ->
737
                let v = pv_of_ity "exv" xs.xs_ity in
738 739 740
                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
741
          (i,xk)::xl, Mxs.add xs (i,v) xm in
742 743 744 745
        let xl, cxmap = Mxs.fold branch bl ([], xmap) in
        let case_xmap, xmap =
          if case then Some cxmap, xmap else None, cxmap in
        let k = k_expr env lps e0 res ?case_xmap xmap in
746 747 748
        (* catched xsymbols are converted to unique integers,
           so that we can now serialise the "with" clauses
           and avoid capturing the wrong exceptions *)
749 750
        List.fold_left (fun k (i,xk) -> Kseq (k,i,xk)) k xl
    | Eraise (xs, e0) ->
751
        let i, v = Mxs.find xs xmap in
752 753 754
        Kseq (k_expr env lps e0 v xmap, 0, Kcont i)
    | Eassert (Assert, f) ->
        let f = vc_expl None lab expl_assert f in
755 756
        let k = Kseq (Kcut f, 0, k_unit res) in
        inv_of_pure env e.e_loc [f] k
757 758
    | Eassert (Assume, f) ->
        let f = vc_expl None lab expl_assume f in
759 760
        let k = Kval ([res], f) in
        inv_of_pure env e.e_loc [f] k
761 762
    | Eassert (Check, f) ->
        let f = vc_expl None lab expl_check f in
763 764
        let k = Kpar (Kstop f, k_unit res) in
        inv_of_pure env e.e_loc [f] k
765 766
    | Eghost e0
    | Eexn (_,e0) ->
767 768 769 770
        k_expr env lps e0 res xmap
    | Epure t ->
        let t = if t.t_ty <> None then t_lab t else
          t_if_simp (t_lab t) t_bool_true t_bool_false in
771 772
        let k = Klet (res, t, t_true) in
        inv_of_pure env e.e_loc [t] k
773
    | Eabsurd ->
774
        Kstop (vc_expl loc lab expl_absurd t_false)
775
    | Ewhile (e0, invl, varl, e1) ->
776 777 778
        (* [ STOP inv
           | HAVOC ; ASSUME inv ; IF e0 THEN e1 ; STOP inv
                                        ELSE SKIP ] *)
779 780 781
        let init = wp_of_inv None lab expl_loop_init invl in
        let prev = sp_of_inv None lab expl_loop_init invl in
        let keep = wp_of_inv None lab expl_loop_keep invl in
782 783 784 785 786
        let keep, oldies =
          if varl = [] then keep, Mpv.empty else
          let oldies, ovarl = oldify_variant varl in
          let d = decrease env loc lab expl_loop_vari ovarl varl in
          wp_and d keep, oldies in
787 788 789 790
        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
791 792
        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
793 794
        let k = List.fold_right assume_inv iinv k in
        Kpar (j, k_havoc e.e_effect k)
795 796 797 798 799 800 801 802 803 804
    | 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,_) ->
              let s = Mts.find s env.ts_ranges in
              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
805 806 807 808 809 810 811
        let init = wp_of_inv None lab expl_loop_init invl in
        let prev = sp_of_inv None lab expl_loop_init invl in
        let keep = wp_of_inv None lab expl_loop_keep invl in
        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
812
        let expl_bounds f = vc_expl loc lab expl_for_bound f in
813 814
        let i_pl_1 = fs_app pl [i; one] ty_int in
        let b_pl_1 = fs_app pl [b; one] ty_int in
815 816 817
        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
818 819 820 821
        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
822 823 824 825 826 827 828
        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
829
        let k = Kpar (k, Kval ([res], last)) in
830 831
        let k = List.fold_right assume_inv iinv k in
        let k = Kpar (j, k_havoc e.e_effect k) in
Andrei Paskevich's avatar
Andrei Paskevich committed
832 833 834 835 836 837 838 839
        (* [ 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)))
840 841 842 843
  in
  if Slab.mem sp_label e.e_label then Ktag (SP, k) else
  if Slab.mem wp_label e.e_label then Ktag (WP, k) else k

844
and k_fun env lps ?(oldies=Mpv.empty) ?(xmap=Mxs.empty) cty e =
Andrei Paskevich's avatar
Andrei Paskevich committed
845
  (* ASSUME pre ; LET o = arg ; TRY e ; STOP post WITH STOP xpost *)
846 847
  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
848
  let xq = Mxs.mapi (fun xs ql ->
849 850
    let v, xq = wp_of_post expl_xpost xs.xs_ity ql in
    (new_exn env, v), xq) xq in
851
  let xmap = Mxs.set_union (Mxs.map fst xq) xmap in
852 853 854 855
  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
856 857 858 859 860 861 862 863
  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 to add the redundant commits and let them be
       eliminated by Typeinv.inject later. *)
    let rinv = inv_of_pvs env e.e_loc (Spv.singleton v) in
    let k = List.fold_right assert_inv rinv (Kstop q) in
    List.fold_right assert_inv qinv k in
864 865 866
  let k = Kseq (k_expr env lps e res xmap, 0, add_qinv res q) in
  let k = Mxs.fold (fun _ ((i,r), xq) k ->
    Kseq (k, i, add_qinv r xq)) xq k in
867 868 869 870
  (* move the postconditions under the VCgen tag *)
  let k = if Slab.mem sp_label e.e_label then Ktag (SP, k) else
          if Slab.mem wp_label e.e_label then Ktag (WP, k) else k in
  let k = bind_oldies oldies (bind_oldies cty.cty_oldies k) in
871 872
  let p = List.fold_right sp_and pinv (sp_of_pre cty.cty_pre) in
  Kseq (Kval (cty.cty_args, p), 0, k)
873 874 875 876 877 878

and k_rec env lps rdl =
  let k_rd {rec_fun = c; rec_varl = varl} =
    let e = match c.c_node with
      | Cfun e -> e | _ -> assert false in
    if varl = [] then k_fun env lps c.c_cty e else
879 880 881
    (* store in lps our variant at the entry point
       and the list of well-founded orderings
       for each function in the let-rec block *)
882
    let oldies, varl = oldify_variant varl in
883 884 885
    let add lps rd =
      let decr = Opt.get (ls_decr_of_rec_defn rd) in
      Mls.add decr (varl, List.map snd rd.rec_varl) lps in
886 887 888
    k_fun env (List.fold_left add lps rdl) ~oldies c.c_cty e in
  List.map k_rd rdl

889
(* stage 2: push sub-expressions up as far as we can *)
890

891 892 893 894 895
(* remove dead code, reassociate sequences to the right,
   and move exception-handling code to the raise site
   when there is only one. This reduces duplication of
   premises for SP and allows it to use let-in instead
   of quantifiers over an equality when possible. *)
896 897 898
let reflow vc_wp k =
  let join _ _ _ = Some false in
  let join = Mint.union join in
899 900 901 902 903
  (* count the exit points for every outcome, normal or
     exceptional; remove the subsequent code if none,
     tag the subsequent code for moving up if single.
     For every kode to be pushed up, remember if
     it can exit normally (open) or not (closed). *)
904
  let rec mark vc_tag k = match k with
Andrei Paskevich's avatar
Andrei Paskevich committed
905 906 907
    | Kseq ((Khavoc _ | Klet _ | Kval _ | Kcut _) as k1, 0, k2) ->
        let k2, out2 = mark vc_tag k2 in
        Kseq (k1, 0, k2), out2
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    | Kseq (k1, i, k2) ->
        let k1, out1 = mark vc_tag k1 in
        begin match Mint.find_opt i out1 with
        | Some push ->
            let k2, out2 = mark vc_tag k2 in
            let k2 = if not push then k2 else
              Ktag (Push (not (Mint.mem 0 out2)), k2) in
            Kseq (k1, i, k2), join (Mint.