file_name
stringlengths
5
52
name
stringlengths
4
95
original_source_type
stringlengths
0
23k
source_type
stringlengths
9
23k
source_definition
stringlengths
9
57.9k
source
dict
source_range
dict
file_context
stringlengths
0
721k
dependencies
dict
opens_and_abbrevs
listlengths
2
94
vconfig
dict
interleaved
bool
1 class
verbose_type
stringlengths
1
7.42k
effect
stringclasses
118 values
effect_flags
sequencelengths
0
2
mutual_with
sequencelengths
0
11
ideal_premises
sequencelengths
0
236
proof_features
sequencelengths
0
1
is_simple_lemma
bool
2 classes
is_div
bool
2 classes
is_proof
bool
2 classes
is_simply_typed
bool
2 classes
is_type
bool
2 classes
partial_definition
stringlengths
5
3.99k
completed_definiton
stringlengths
1
1.63M
isa_cross_project_example
bool
1 class
Steel.Effect.Common.fsti
Steel.Effect.Common.is_and
val is_and (t: term) : bool
val is_and (t: term) : bool
let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and]
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 36, "end_line": 1771, "start_col": 0, "start_line": 1770 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.NamedView.term", "FStar.Reflection.V2.Derived.is_any_fvar", "Prims.Cons", "Prims.string", "Prims.Nil", "Prims.bool" ]
[]
false
false
false
true
false
let is_and (t: term) : bool =
is_any_fvar t [`%( /\ ); `%prop_and]
false
Steel.Effect.Common.fsti
Steel.Effect.Common.is_squash
val is_squash (t: term) : bool
val is_squash (t: term) : bool
let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash]
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 41, "end_line": 1775, "start_col": 0, "start_line": 1774 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and]
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.NamedView.term", "FStar.Reflection.V2.Derived.is_any_fvar", "Prims.Cons", "Prims.string", "Prims.Nil", "Prims.bool" ]
[]
false
false
false
true
false
let is_squash (t: term) : bool =
is_any_fvar t [`%squash; `%auto_squash]
false
Steel.Effect.Common.fsti
Steel.Effect.Common.mdenote_gen
val mdenote_gen (#a: Type u#aa) (unit: a) (mult: (a -> a -> a)) (am: amap a) (e: exp) : a
val mdenote_gen (#a: Type u#aa) (unit: a) (mult: (a -> a -> a)) (am: amap a) (e: exp) : a
let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 82, "end_line": 1119, "start_col": 0, "start_line": 1115 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
unit: a -> mult: (_: a -> _: a -> a) -> am: Steel.Effect.Common.amap a -> e: Steel.Effect.Common.exp -> a
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.amap", "Steel.Effect.Common.exp", "Steel.Effect.Common.atom", "Steel.Effect.Common.select", "Steel.Effect.Common.mdenote_gen" ]
[ "recursion" ]
false
false
false
true
false
let rec mdenote_gen (#a: Type u#aa) (unit: a) (mult: (a -> a -> a)) (am: amap a) (e: exp) : a =
match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.close_equality_typ
val close_equality_typ (t: term) : Tac unit
val close_equality_typ (t: term) : Tac unit
let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 32, "end_line": 1716, "start_col": 0, "start_line": 1715 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> ()
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Steel.Effect.Common.visit_tm", "Steel.Effect.Common.close_equality_typ'", "Prims.unit" ]
[]
false
true
false
false
false
let close_equality_typ (t: term) : Tac unit =
visit_tm close_equality_typ' t
false
Steel.Effect.Common.fsti
Steel.Effect.Common.xsdenote_gen
val xsdenote_gen (#a: Type) (unit: a) (mult: (a -> a -> a)) (am: amap a) (xs: list atom) : a
val xsdenote_gen (#a: Type) (unit: a) (mult: (a -> a -> a)) (am: amap a) (xs: list atom) : a
let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs')
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 64, "end_line": 1125, "start_col": 0, "start_line": 1121 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
unit: a -> mult: (_: a -> _: a -> a) -> am: Steel.Effect.Common.amap a -> xs: Prims.list Steel.Effect.Common.atom -> a
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.amap", "Prims.list", "Steel.Effect.Common.atom", "Steel.Effect.Common.select", "Steel.Effect.Common.xsdenote_gen" ]
[ "recursion" ]
false
false
false
true
false
let rec xsdenote_gen (#a: Type) (unit: a) (mult: (a -> a -> a)) (am: amap a) (xs: list atom) : a =
match xs with | [] -> unit | [x] -> select x am | x :: xs' -> mult (select x am) (xsdenote_gen unit mult am xs')
false
Steel.Effect.Common.fsti
Steel.Effect.Common.monoid_reflect
val monoid_reflect: #a: Type -> eq: CE.equiv a -> m: CE.cm a eq -> am: amap a -> e1: exp -> e2: exp -> squash (CE.EQ?.eq eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) -> squash (CE.EQ?.eq eq (mdenote eq m am e1) (mdenote eq m am e2))
val monoid_reflect: #a: Type -> eq: CE.equiv a -> m: CE.cm a eq -> am: amap a -> e1: exp -> e2: exp -> squash (CE.EQ?.eq eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) -> squash (CE.EQ?.eq eq (mdenote eq m am e1) (mdenote eq m am e2))
let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 26, "end_line": 1210, "start_col": 0, "start_line": 1197 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2))
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> am: Steel.Effect.Common.amap a -> e1: Steel.Effect.Common.exp -> e2: Steel.Effect.Common.exp -> _: Prims.squash (EQ?.eq eq (Steel.Effect.Common.xsdenote eq m am (Steel.Effect.Common.flatten e1)) (Steel.Effect.Common.xsdenote eq m am (Steel.Effect.Common.flatten e2))) -> Prims.squash (EQ?.eq eq (Steel.Effect.Common.mdenote eq m am e1) (Steel.Effect.Common.mdenote eq m am e2))
Prims.Tot
[ "total" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "Steel.Effect.Common.amap", "Steel.Effect.Common.exp", "Prims.squash", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Steel.Effect.Common.xsdenote", "Steel.Effect.Common.flatten", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__transitivity", "Steel.Effect.Common.mdenote", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "Steel.Effect.Common.flatten_correct" ]
[]
false
false
true
false
false
let monoid_reflect (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (e1: exp) (e2: exp) (_: squash (CE.EQ?.eq eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)))) : squash (CE.EQ?.eq eq (mdenote eq m am e1) (mdenote eq m am e2)) =
flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.flatten_correct
val flatten_correct (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (e: exp) : Lemma (CE.EQ?.eq eq (mdenote eq m am e) (xsdenote eq m am (flatten e)))
val flatten_correct (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (e: exp) : Lemma (CE.EQ?.eq eq (mdenote eq m am e) (xsdenote eq m am (flatten e)))
let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2))
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 80, "end_line": 1195, "start_col": 0, "start_line": 1179 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2))
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> am: Steel.Effect.Common.amap a -> e: Steel.Effect.Common.exp -> FStar.Pervasives.Lemma (ensures EQ?.eq eq (Steel.Effect.Common.mdenote eq m am e) (Steel.Effect.Common.xsdenote eq m am (Steel.Effect.Common.flatten e)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "Steel.Effect.Common.amap", "Steel.Effect.Common.exp", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__reflexivity", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit", "Steel.Effect.Common.atom", "Steel.Effect.Common.select", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__transitivity", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult", "Steel.Effect.Common.mdenote", "Steel.Effect.Common.xsdenote", "Steel.Effect.Common.flatten", "Steel.Effect.Common.my_append", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__congruence", "Steel.Effect.Common.flatten_correct", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "Steel.Effect.Common.flatten_correct_aux", "Prims.l_True", "Prims.squash", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Prims.Nil", "FStar.Pervasives.pattern" ]
[ "recursion" ]
false
false
true
false
false
let rec flatten_correct (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (e: exp) : Lemma (CE.EQ?.eq eq (mdenote eq m am e) (xsdenote eq m am (flatten e))) =
let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am ((flatten e1) `my_append` (flatten e2))) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am ((flatten e1) `my_append` (flatten e2)))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.identity_left
val identity_left (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x: a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x))
val identity_left (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x: a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x))
let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 58, "end_line": 1544, "start_col": 0, "start_line": 1541 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> x: a -> FStar.Pervasives.Lemma (ensures EQ?.eq eq x (CM?.mult m (CM?.unit m) x))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__identity", "Prims.l_True", "Prims.squash", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
true
false
true
false
false
let identity_left (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x: a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) =
CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x
false
Steel.Effect.Common.fsti
Steel.Effect.Common.is_star
val is_star (t: term) : bool
val is_star (t: term) : bool
let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar]
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 33, "end_line": 1779, "start_col": 0, "start_line": 1778 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash]
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.NamedView.term", "FStar.Reflection.V2.Derived.is_any_fvar", "Prims.Cons", "Prims.string", "Prims.Nil", "Prims.bool" ]
[]
false
false
false
true
false
let is_star (t: term) : bool =
is_any_fvar t [`%star; `%VStar]
false
Steel.Effect.Common.fsti
Steel.Effect.Common.identity_right_diff
val identity_right_diff (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x y: a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y)
val identity_right_diff (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x y: a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y)
let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 64, "end_line": 1550, "start_col": 0, "start_line": 1546 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> x: a -> y: a -> FStar.Pervasives.Lemma (requires EQ?.eq eq x y) (ensures EQ?.eq eq (CM?.mult m x (CM?.unit m)) y)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__transitivity", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.right_identity", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Prims.squash", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
true
false
true
false
false
let identity_right_diff (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x y: a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) =
CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y
false
Steel.Effect.Common.fsti
Steel.Effect.Common.flatten_correct_aux
val flatten_correct_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (xs1 xs2: list atom) : Lemma (CE.EQ?.eq eq (xsdenote eq m am (xs1 `my_append` xs2)) (CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)))
val flatten_correct_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (xs1 xs2: list atom) : Lemma (CE.EQ?.eq eq (xsdenote eq m am (xs1 `my_append` xs2)) (CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)))
let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2))
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 112, "end_line": 1177, "start_col": 0, "start_line": 1154 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> am: Steel.Effect.Common.amap a -> xs1: Prims.list Steel.Effect.Common.atom -> xs2: Prims.list Steel.Effect.Common.atom -> FStar.Pervasives.Lemma (ensures EQ?.eq eq (Steel.Effect.Common.xsdenote eq m am (Steel.Effect.Common.my_append xs1 xs2)) (CM?.mult m (Steel.Effect.Common.xsdenote eq m am xs1) (Steel.Effect.Common.xsdenote eq m am xs2)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "Steel.Effect.Common.amap", "Prims.list", "Steel.Effect.Common.atom", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit", "Steel.Effect.Common.xsdenote", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__identity", "Prims.uu___is_Nil", "Steel.Effect.Common.select", "FStar.Algebra.CommMonoid.Equiv.right_identity", "Prims.bool", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__reflexivity", "Prims.Cons", "Prims.Nil", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__transitivity", "Steel.Effect.Common.my_append", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__associativity", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__congruence", "Steel.Effect.Common.flatten_correct_aux", "Prims.l_True", "Prims.squash", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "FStar.Pervasives.pattern" ]
[ "recursion" ]
false
false
true
false
false
let rec flatten_correct_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (xs1 xs2: list atom) : Lemma (CE.EQ?.eq eq (xsdenote eq m am (xs1 `my_append` xs2)) (CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2))) =
let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> (if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x :: xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.my_partition
val my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l))
val my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l))
let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 20, "end_line": 1226, "start_col": 0, "start_line": 1216 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it,
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: a -> Prims.bool) -> l: Prims.list a -> Prims.Pure (Prims.list a * Prims.list a)
Prims.Pure
[]
[]
[ "Prims.bool", "Prims.list", "FStar.Pervasives.Native.Mktuple2", "Prims.Nil", "Prims.Cons", "FStar.Pervasives.Native.tuple2", "Steel.Effect.Common.my_partition", "Prims.l_True", "Prims.eq2", "FStar.List.Tot.Base.partition" ]
[ "recursion" ]
false
false
false
false
false
let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) =
match l with | [] -> [], [] | hd :: tl -> let l1, l2 = my_partition f tl in if f hd then hd :: l1, l2 else l1, hd :: l2
false
Steel.Effect.Common.fsti
Steel.Effect.Common.is_star_or_unit
val is_star_or_unit (t: term) : bool
val is_star_or_unit (t: term) : bool
let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit]
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 42, "end_line": 1783, "start_col": 0, "start_line": 1782 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar]
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.NamedView.term", "FStar.Reflection.V2.Derived.is_any_fvar", "Prims.Cons", "Prims.string", "Prims.Nil", "Prims.bool" ]
[]
false
false
false
true
false
let is_star_or_unit (t: term) : bool =
is_any_fvar t [`%star; `%VStar; `%VUnit]
false
Steel.Effect.Common.fsti
Steel.Effect.Common.my_append
val my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1)
val my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1)
let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 33, "end_line": 1146, "start_col": 0, "start_line": 1140 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l1: Prims.list t -> l2: Prims.list t -> Prims.Pure (Prims.list t)
Prims.Pure
[ "" ]
[]
[ "Prims.list", "Prims.Cons", "Steel.Effect.Common.my_append", "Prims.l_True", "Prims.eq2", "FStar.List.Tot.Base.append" ]
[ "recursion" ]
false
false
false
false
false
let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) =
match l1 with | [] -> l2 | a :: q -> a :: my_append q l2
false
Steel.Effect.Common.fsti
Steel.Effect.Common._return_squash
val _return_squash: #a: Type -> Prims.unit -> x: a -> Tot (squash a)
val _return_squash: #a: Type -> Prims.unit -> x: a -> Tot (squash a)
let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 30, "end_line": 1824, "start_col": 0, "start_line": 1823 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h))
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> x: a -> Prims.squash a
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "FStar.Squash.return_squash", "Prims.squash" ]
[]
false
false
true
true
false
let _return_squash (#a: Type) () (x: a) : Tot (squash a) =
FStar.Squash.return_squash x
false
Steel.Effect.Common.fsti
Steel.Effect.Common.sortWith_ext
val sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y. f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l))
val sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y. f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l))
let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 25, "end_line": 1264, "start_col": 0, "start_line": 1252 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f1: (_: a -> _: a -> Prims.int) -> f2: (_: a -> _: a -> Prims.int) -> l: Prims.list a -> FStar.Pervasives.Lemma (requires forall (x: a) (y: a). f1 x y == f2 x y) (ensures FStar.List.Tot.Base.sortWith f1 l == FStar.List.Tot.Base.sortWith f2 l) (decreases FStar.List.Tot.Base.length l)
FStar.Pervasives.Lemma
[ "lemma", "" ]
[]
[ "Prims.int", "Prims.list", "Steel.Effect.Common.sortWith_ext", "Prims.unit", "FStar.Pervasives.Native.tuple2", "FStar.List.Tot.Base.partition", "FStar.List.Tot.Base.bool_of_compare", "FStar.List.Tot.Base.partition_length", "Steel.Effect.Common.partition_ext", "Prims.l_Forall", "Prims.eq2", "Prims.squash", "FStar.List.Tot.Base.sortWith", "Prims.Nil", "FStar.Pervasives.pattern" ]
[ "recursion" ]
false
false
true
false
false
let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y. f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) =
match l with | [] -> () | pivot :: tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi
false
Steel.Effect.Common.fsti
Steel.Effect.Common.identity_left_smt
val identity_left_smt (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x y: a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y))
val identity_left_smt (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x y: a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y))
let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 58, "end_line": 1539, "start_col": 0, "start_line": 1534 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> x: a -> y: a -> FStar.Pervasives.Lemma (requires x == y) (ensures EQ?.eq eq x (CM?.mult m (CM?.unit m) y))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__identity", "Prims.eq2", "Prims.squash", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
true
false
true
false
false
let identity_left_smt (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (x y: a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) =
CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x
false
Steel.Effect.Common.fsti
Steel.Effect.Common.smt_reflexivity
val smt_reflexivity (#a: Type) (eq: CE.equiv a) (x y: a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y)
val smt_reflexivity (#a: Type) (eq: CE.equiv a) (x y: a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y)
let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 27, "end_line": 1532, "start_col": 0, "start_line": 1529 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> x: a -> y: a -> FStar.Pervasives.Lemma (requires x == y) (ensures EQ?.eq eq x y)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__reflexivity", "Prims.unit", "Prims.eq2", "Prims.squash", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
true
false
true
false
false
let smt_reflexivity (#a: Type) (eq: CE.equiv a) (x y: a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) =
CE.EQ?.reflexivity eq x
false
Steel.Effect.Common.fsti
Steel.Effect.Common.canon'
val canon' (use_smt: bool) (pr pr_bind: term) : Tac unit
val canon' (use_smt: bool) (pr pr_bind: term) : Tac unit
let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 83, "end_line": 2107, "start_col": 0, "start_line": 2106 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation")
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
use_smt: Prims.bool -> pr: FStar.Tactics.NamedView.term -> pr_bind: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.bool", "FStar.Tactics.NamedView.term", "Steel.Effect.Common.canon_monoid", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_FVar", "FStar.Stubs.Reflection.V2.Builtins.pack_fv", "Prims.Cons", "Prims.string", "Prims.Nil", "Prims.unit" ]
[]
false
true
false
false
false
let canon' (use_smt: bool) (pr pr_bind: term) : Tac unit =
canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind
false
Steel.Effect.Common.fsti
Steel.Effect.Common.partition_ext
val partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x. f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l))
val partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x. f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l))
let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 36, "end_line": 1234, "start_col": 0, "start_line": 1228 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f1: (_: a -> Prims.bool) -> f2: (_: a -> Prims.bool) -> l: Prims.list a -> FStar.Pervasives.Lemma (requires forall (x: a). f1 x == f2 x) (ensures FStar.List.Tot.Base.partition f1 l == FStar.List.Tot.Base.partition f2 l)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Prims.bool", "Prims.list", "Steel.Effect.Common.partition_ext", "Prims.unit", "Prims.l_Forall", "Prims.eq2", "Prims.squash", "FStar.Pervasives.Native.tuple2", "FStar.List.Tot.Base.partition", "Prims.Nil", "FStar.Pervasives.pattern" ]
[ "recursion" ]
false
false
true
false
false
let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x. f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) =
match l with | [] -> () | hd :: tl -> partition_ext f1 f2 tl
false
Steel.Effect.Common.fsti
Steel.Effect.Common.list_to_string
val list_to_string (l: list term) : Tac string
val list_to_string (l: list term) : Tac string
let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 57, "end_line": 1113, "start_col": 0, "start_line": 1110 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Prims.list FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.string
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Tactics.NamedView.term", "Prims.string", "Prims.op_Hat", "Steel.Effect.Common.list_to_string", "FStar.Stubs.Tactics.V2.Builtins.term_to_string" ]
[ "recursion" ]
false
true
false
false
false
let rec list_to_string (l: list term) : Tac string =
match l with | [] -> "end" | hd :: tl -> term_to_string hd ^ " " ^ list_to_string tl
false
Steel.Effect.Common.fsti
Steel.Effect.Common.my_sortWith
val my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l: list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l))
val my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l: list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l))
let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 59, "end_line": 1250, "start_col": 0, "start_line": 1239 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: a -> _: a -> Prims.int) -> l: Prims.list a -> Prims.Pure (Prims.list a)
Prims.Pure
[ "" ]
[]
[ "Prims.int", "Prims.list", "Prims.Nil", "Steel.Effect.Common.my_append", "Steel.Effect.Common.my_sortWith", "Prims.Cons", "Prims.unit", "FStar.List.Tot.Base.partition_length", "FStar.List.Tot.Base.bool_of_compare", "Steel.Effect.Common.partition_ext", "Steel.Effect.Common.my_bool_of_compare", "FStar.Pervasives.Native.tuple2", "Steel.Effect.Common.my_partition", "Prims.l_True", "Prims.eq2", "FStar.List.Tot.Base.sortWith" ]
[ "recursion" ]
false
false
false
false
false
let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l: list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) =
match l with | [] -> [] | pivot :: tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot :: my_sortWith f hi)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.slterm_nbr_uvars
val slterm_nbr_uvars (t: term) : Tac int
val slterm_nbr_uvars (t: term) : Tac int
let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 59, "end_line": 2124, "start_col": 0, "start_line": 2110 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.int
FStar.Tactics.Effect.Tac
[]
[ "slterm_nbr_uvars", "slterm_nbr_uvars_argv" ]
[ "FStar.Tactics.NamedView.term", "Prims.nat", "FStar.Stubs.Reflection.Types.ctx_uvar_and_subst", "Prims.int", "FStar.Stubs.Reflection.V2.Data.argv", "Prims.list", "Steel.Effect.Common.is_star_or_unit", "Steel.Effect.Common.slterm_nbr_uvars_argv", "Prims.bool", "Steel.Effect.Common.is_uvar", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app", "FStar.Tactics.NamedView.binder", "Steel.Effect.Common.slterm_nbr_uvars", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.NamedView.term_view", "Prims.b2t", "FStar.Tactics.NamedView.notAscription", "FStar.Tactics.V2.SyntaxHelpers.inspect_unascribe" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec slterm_nbr_uvars (t: term) : Tac int =
match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0
false
Steel.Effect.Common.fsti
Steel.Effect.Common.unify_pr_with_true
val unify_pr_with_true (pr: term) : Tac unit
val unify_pr_with_true (pr: term) : Tac unit
let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there")
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 73, "end_line": 1807, "start_col": 0, "start_line": 1785 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit]
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
pr: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "Steel.Effect.Common.is_and", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "Steel.Effect.Common.unify_pr_with_true", "Prims.unit", "FStar.Tactics.V2.Derived.fail", "Prims.bool", "Prims.nat", "FStar.Stubs.Reflection.Types.ctx_uvar_and_subst", "FStar.Tactics.V2.Derived.unify", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.Effect.raise", "Steel.Effect.Common.Postpone", "Prims.op_Equality", "Prims.int", "FStar.List.Tot.Base.length", "FStar.Stubs.Tactics.V2.Builtins.free_uvars", "FStar.Tactics.NamedView.term_view", "Prims.b2t", "FStar.Tactics.NamedView.notAscription", "FStar.Tactics.V2.SyntaxHelpers.inspect_unascribe", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app" ]
[ "recursion" ]
false
true
false
false
false
let rec unify_pr_with_true (pr: term) : Tac unit =
let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _ ; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else fail "unify_pr_with_true: could not unify SMT prop with True" | _ -> if List.Tot.length (free_uvars pr) = 0 then () else raise (Postpone "unify_pr_with_true: some uvars are still there")
false
Steel.Effect.Common.fsti
Steel.Effect.Common.equivalent_sorted
val equivalent_sorted (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (l1 l2 l1' l2': list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ CE.EQ?.eq eq (xsdenote eq m am l1) (xsdenote eq m am l2)) (ensures CE.EQ?.eq eq (xsdenote eq m am l1') (xsdenote eq m am l2'))
val equivalent_sorted (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (l1 l2 l1' l2': list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ CE.EQ?.eq eq (xsdenote eq m am l1) (xsdenote eq m am l2)) (ensures CE.EQ?.eq eq (xsdenote eq m am l1') (xsdenote eq m am l2'))
let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2')
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 28, "end_line": 1602, "start_col": 0, "start_line": 1574 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> am: Steel.Effect.Common.amap a -> l1: Prims.list Steel.Effect.Common.atom -> l2: Prims.list Steel.Effect.Common.atom -> l1': Prims.list Steel.Effect.Common.atom -> l2': Prims.list Steel.Effect.Common.atom -> FStar.Pervasives.Lemma (requires Steel.Effect.Common.sort l1 == Steel.Effect.Common.sort l1' /\ Steel.Effect.Common.sort l2 == Steel.Effect.Common.sort l2' /\ EQ?.eq eq (Steel.Effect.Common.xsdenote eq m am l1) (Steel.Effect.Common.xsdenote eq m am l2)) (ensures EQ?.eq eq (Steel.Effect.Common.xsdenote eq m am l1') (Steel.Effect.Common.xsdenote eq m am l2'))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "Steel.Effect.Common.amap", "Prims.list", "Steel.Effect.Common.atom", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__transitivity", "Steel.Effect.Common.xsdenote", "Steel.Effect.Common.sort", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "Steel.Effect.Common.sort_correct_aux", "Prims.l_and", "Prims.eq2", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Prims.squash", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
true
false
true
false
false
let equivalent_sorted (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (l1 l2 l1' l2': list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ CE.EQ?.eq eq (xsdenote eq m am l1) (xsdenote eq m am l2)) (ensures CE.EQ?.eq eq (xsdenote eq m am l1') (xsdenote eq m am l2')) =
let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2')
false
Steel.Effect.Common.fsti
Steel.Effect.Common.unfold_guard
val unfold_guard: Prims.unit -> Tac bool
val unfold_guard: Prims.unit -> Tac bool
let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 9, "end_line": 2158, "start_col": 0, "start_line": 2152 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Prims.bool", "FStar.Tactics.V2.Derived.focus", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "Steel.Effect.Common.all_guards_solved", "FStar.Tactics.NamedView.term", "FStar.Tactics.V2.Derived.cur_goal", "FStar.Stubs.Reflection.Types.typ" ]
[]
false
true
false
false
false
let unfold_guard () : Tac bool =
if all_guards_solved (cur_goal ()) then (focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true) else false
false
Steel.Effect.Common.fsti
Steel.Effect.Common.guard_vprop
val guard_vprop (v: vprop) : Tot vprop
val guard_vprop (v: vprop) : Tot vprop
let guard_vprop (v: vprop) : Tot vprop = v
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 42, "end_line": 2126, "start_col": 0, "start_line": 2126 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
v: Steel.Effect.Common.vprop -> Steel.Effect.Common.vprop
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.vprop" ]
[]
false
false
false
true
false
let guard_vprop (v: vprop) : Tot vprop =
v
false
Steel.Effect.Common.fsti
Steel.Effect.Common.fatom
val fatom (t: term) (ts: list term) (am: amap term) : Tac (exp * list term * amap term)
val fatom (t: term) (ts: list term) (am: amap term) : Tac (exp * list term * amap term)
let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 63, "end_line": 1621, "start_col": 0, "start_line": 1615 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> ts: Prims.list FStar.Tactics.NamedView.term -> am: Steel.Effect.Common.amap FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac ((Steel.Effect.Common.exp * Prims.list FStar.Tactics.NamedView.term) * Steel.Effect.Common.amap FStar.Tactics.NamedView.term)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "Steel.Effect.Common.amap", "Prims.nat", "FStar.Pervasives.Native.Mktuple3", "Steel.Effect.Common.exp", "Steel.Effect.Common.Atom", "FStar.Pervasives.Native.tuple3", "FStar.List.Tot.Base.append", "Prims.Cons", "Prims.Nil", "Steel.Effect.Common.update", "FStar.Tactics.V2.Derived.norm_term", "FStar.Pervasives.norm_step", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.List.Tot.Base.length", "FStar.Pervasives.Native.option", "Steel.Effect.Common.where" ]
[]
false
true
false
false
false
let fatom (t: term) (ts: list term) (am: amap term) : Tac (exp * list term * amap term) =
match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.where_aux
val where_aux (n: nat) (x: term) (xs: list term) : Tac (option nat) (decreases xs)
val where_aux (n: nat) (x: term) (xs: list term) : Tac (option nat) (decreases xs)
let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs'
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 73, "end_line": 1612, "start_col": 0, "start_line": 1608 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs.
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
n: Prims.nat -> x: FStar.Tactics.NamedView.term -> xs: Prims.list FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Pervasives.Native.option Prims.nat)
FStar.Tactics.Effect.Tac
[ "" ]
[]
[ "Prims.nat", "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.Some", "Prims.bool", "Steel.Effect.Common.where_aux", "Prims.op_Addition", "FStar.Stubs.Tactics.V2.Builtins.term_eq_old" ]
[ "recursion" ]
false
true
false
false
false
let rec where_aux (n: nat) (x: term) (xs: list term) : Tac (option nat) (decreases xs) =
match xs with | [] -> None | x' :: xs' -> if term_eq_old x x' then Some n else where_aux (n + 1) x xs'
false
Steel.Effect.Common.fsti
Steel.Effect.Common.convert_map
val convert_map (m: list (atom * term)) : term
val convert_map (m: list (atom * term)) : term
let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps)))
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 45, "end_line": 1657, "start_col": 0, "start_line": 1651 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
m: Prims.list (Steel.Effect.Common.atom * FStar.Tactics.NamedView.term) -> FStar.Tactics.NamedView.term
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "FStar.Pervasives.Native.tuple2", "Steel.Effect.Common.atom", "FStar.Tactics.NamedView.term", "FStar.Stubs.Reflection.Types.term", "Steel.Effect.Common.convert_map", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Const", "FStar.Stubs.Reflection.V2.Data.C_Int" ]
[ "recursion" ]
false
false
false
true
false
let rec convert_map (m: list (atom * term)) : term =
match m with | [] -> `[] | (a, t) :: ps -> let a = pack (Tv_Const (C_Int a)) in `(((`#a), (`#t)) :: (`#(convert_map ps)))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.try_open_existentials
val try_open_existentials: Prims.unit -> Tac bool
val try_open_existentials: Prims.unit -> Tac bool
let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false )
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 3, "end_line": 2334, "start_col": 0, "start_line": 2328 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "FStar.Tactics.V2.Derived.focus", "Prims.bool", "FStar.Tactics.V2.Derived.try_with", "Steel.Effect.Common.open_existentials", "Prims.exn" ]
[]
false
true
false
false
false
let try_open_existentials () : Tac bool =
focus (fun _ -> try (open_existentials (); true) with | _ -> false)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.set_abduction_variable
val set_abduction_variable: Prims.unit -> Tac unit
val set_abduction_variable: Prims.unit -> Tac unit
let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 33, "end_line": 1856, "start_col": 0, "start_line": 1850 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "FStar.Tactics.NamedView.binder", "FStar.Tactics.NamedView.comp", "FStar.Tactics.V2.Derived.exact", "FStar.Tactics.NamedView.term", "Steel.Effect.Common.set_abduction_variable_term", "FStar.Stubs.Reflection.Types.typ", "FStar.Tactics.NamedView.__proj__Mkbinder__item__sort", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.V2.Derived.fail", "FStar.Tactics.NamedView.term_view", "Prims.b2t", "FStar.Tactics.NamedView.notAscription", "FStar.Tactics.V2.SyntaxHelpers.inspect_unascribe", "FStar.Tactics.V2.Derived.cur_goal" ]
[]
false
true
false
false
false
let set_abduction_variable () : Tac unit =
let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.dismiss_non_squash_goals
val dismiss_non_squash_goals : _: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 32, "end_line": 2196, "start_col": 0, "start_line": 2194 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Steel.Effect.Common.dismiss_non_squash_goals'", "Prims.Nil", "FStar.Stubs.Tactics.Types.goal", "Prims.list", "FStar.Tactics.V2.Derived.goals" ]
[]
false
true
false
false
false
let dismiss_non_squash_goals () =
let g = goals () in dismiss_non_squash_goals' [] g
false
Steel.Effect.Common.fsti
Steel.Effect.Common.dismiss_all_but_last
val dismiss_all_but_last: Prims.unit -> Tac unit
val dismiss_all_but_last: Prims.unit -> Tac unit
let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ())
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 34, "end_line": 2177, "start_col": 0, "start_line": 2176 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Steel.Effect.Common.dismiss_all_but_last'", "Prims.list", "FStar.Stubs.Tactics.Types.goal", "FStar.Tactics.V2.Derived.goals" ]
[]
false
true
false
false
false
let dismiss_all_but_last () : Tac unit =
dismiss_all_but_last' (goals ())
false
Steel.Effect.Common.fsti
Steel.Effect.Common.quote_atoms
val quote_atoms : l: Prims.list Steel.Effect.Common.atom -> FStar.Stubs.Reflection.Types.term
let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl)))
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 49, "end_line": 1679, "start_col": 0, "start_line": 1676 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt))
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Prims.list Steel.Effect.Common.atom -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Steel.Effect.Common.atom", "FStar.Stubs.Reflection.Types.term", "Steel.Effect.Common.quote_atoms", "FStar.Tactics.NamedView.term", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Const", "FStar.Stubs.Reflection.V2.Data.C_Int" ]
[ "recursion" ]
false
false
false
true
false
let rec quote_atoms (l: list atom) =
match l with | [] -> `[] | hd :: tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl)))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.all_guards_solved
val all_guards_solved (t: term) : Tac bool
val all_guards_solved (t: term) : Tac bool
let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 13, "end_line": 2150, "start_col": 0, "start_line": 2128 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "FStar.Tactics.NamedView.binder", "Steel.Effect.Common.all_guards_solved", "Prims.bool", "FStar.Stubs.Reflection.V2.Data.argv", "Prims.list", "FStar.Reflection.V2.Derived.is_fvar", "Prims.op_Equality", "Prims.int", "Steel.Effect.Common.slterm_nbr_uvars_argv", "FStar.List.Tot.Base.fold_left", "Prims.unit", "FStar.Pervasives.Native.tuple2", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.op_Negation", "FStar.Tactics.V2.SyntaxHelpers.collect_app", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.NamedView.term_view", "Prims.b2t", "FStar.Tactics.NamedView.notAscription", "FStar.Tactics.V2.SyntaxHelpers.inspect_unascribe" ]
[ "recursion" ]
false
true
false
false
false
let rec all_guards_solved (t: term) : Tac bool =
match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f) (let f () : Tac bool = true in f) args () | _ -> true
false
Steel.Effect.Common.fsti
Steel.Effect.Common.term_is_uvar
val term_is_uvar (t: term) (i: int) : Tac bool
val term_is_uvar (t: term) (i: int) : Tac bool
let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 14, "end_line": 2165, "start_col": 0, "start_line": 2160 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> i: Prims.int -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.int", "Prims.nat", "FStar.Stubs.Reflection.Types.ctx_uvar_and_subst", "Prims.op_Equality", "Prims.bool", "FStar.Stubs.Reflection.V2.Data.argv", "Prims.list", "Steel.Effect.Common.term_is_uvar", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.NamedView.inspect" ]
[ "recursion" ]
false
true
false
false
false
let rec term_is_uvar (t: term) (i: int) : Tac bool =
match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false
false
Steel.Effect.Common.fsti
Steel.Effect.Common.lookup_by_term_attr
val lookup_by_term_attr (label_attr attr: term) : Tac (list fv)
val lookup_by_term_attr (label_attr attr: term) : Tac (list fv)
let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 43, "end_line": 2224, "start_col": 0, "start_line": 2221 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
label_attr: FStar.Tactics.NamedView.term -> attr: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (Prims.list FStar.Stubs.Reflection.Types.fv)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Steel.Effect.Common.lookup_by_term_attr'", "Prims.Nil", "FStar.Stubs.Reflection.Types.fv", "Prims.list", "FStar.Stubs.Reflection.V2.Builtins.lookup_attr", "FStar.Stubs.Reflection.Types.env", "FStar.Tactics.V2.Derived.cur_env" ]
[]
false
true
false
false
false
let lookup_by_term_attr (label_attr attr: term) : Tac (list fv) =
let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates
false
Steel.Effect.Common.fsti
Steel.Effect.Common.lemma_xsdenote_aux
val lemma_xsdenote_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (hd: atom) (tl: list atom) : Lemma (CE.EQ?.eq eq (xsdenote eq m am (hd :: tl)) (CE.CM?.mult m (select hd am) (xsdenote eq m am tl)) )
val lemma_xsdenote_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (hd: atom) (tl: list atom) : Lemma (CE.EQ?.eq eq (xsdenote eq m am (hd :: tl)) (CE.CM?.mult m (select hd am) (xsdenote eq m am tl)) )
let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl))
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 57, "end_line": 1291, "start_col": 0, "start_line": 1277 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 1, "initial_ifuel": 1, "max_fuel": 1, "max_ifuel": 1, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> am: Steel.Effect.Common.amap a -> hd: Steel.Effect.Common.atom -> tl: Prims.list Steel.Effect.Common.atom -> FStar.Pervasives.Lemma (ensures EQ?.eq eq (Steel.Effect.Common.xsdenote eq m am (hd :: tl)) (CM?.mult m (Steel.Effect.Common.select hd am) (Steel.Effect.Common.xsdenote eq m am tl)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "Steel.Effect.Common.amap", "Steel.Effect.Common.atom", "Prims.list", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__transitivity", "Steel.Effect.Common.xsdenote", "Prims.Cons", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit", "Steel.Effect.Common.select", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__commutativity", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__identity", "Prims._assert", "Prims.eq2", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__reflexivity", "Prims.l_True", "Prims.squash", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
false
false
true
false
false
let lemma_xsdenote_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (hd: atom) (tl: list atom) : Lemma (CE.EQ?.eq eq (xsdenote eq m am (hd :: tl)) (CE.CM?.mult m (select hd am) (xsdenote eq m am tl)) ) =
let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd :: tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (select hd am)) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd :: tl)) (CM?.mult m (CM?.unit m) (select hd am)) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd :: tl))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.extract_cbs_contexts
val extract_cbs_contexts : t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Pervasives.Native.option (_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit))
let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 27, "end_line": 2298, "start_col": 0, "start_line": 2294 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () )
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Pervasives.Native.option (_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit))
FStar.Tactics.Effect.Tac
[]
[]
[ "Steel.Effect.Common.extract_contexts" ]
[]
false
true
false
false
false
let extract_cbs_contexts =
extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.set_abduction_variable_term
val set_abduction_variable_term (pr: term) : Tac term
val set_abduction_variable_term (pr: term) : Tac term
let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 54, "end_line": 1848, "start_col": 0, "start_line": 1826 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
pr: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "Steel.Effect.Common.is_and", "FStar.Stubs.Reflection.Types.term", "FStar.Reflection.V2.Derived.mk_app", "Prims.Cons", "FStar.Pervasives.Native.Mktuple2", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Prims.Nil", "Steel.Effect.Common.set_abduction_variable_term", "Prims.bool", "FStar.Tactics.Effect.raise", "Steel.Effect.Common.Postpone", "Prims.op_Equality", "Prims.int", "FStar.List.Tot.Base.length", "FStar.Stubs.Tactics.V2.Builtins.free_uvars", "FStar.Tactics.V2.Derived.fail", "Prims.nat", "FStar.Stubs.Reflection.Types.ctx_uvar_and_subst", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.NamedView.inspect", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app" ]
[ "recursion" ]
false
true
false
false
false
let rec set_abduction_variable_term (pr: term) : Tac term =
let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [(`()), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.sort_correct_aux
val sort_correct_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (xs: list atom) : Lemma (requires True) (ensures CE.EQ?.eq eq (xsdenote eq m am xs) (xsdenote eq m am (sort xs))) (decreases (FStar.List.Tot.Base.length xs))
val sort_correct_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (xs: list atom) : Lemma (requires True) (ensures CE.EQ?.eq eq (xsdenote eq m am xs) (xsdenote eq m am (sort xs))) (decreases (FStar.List.Tot.Base.length xs))
let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 72, "end_line": 1521, "start_col": 0, "start_line": 1413 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 1, "initial_ifuel": 1, "max_fuel": 1, "max_ifuel": 1, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> am: Steel.Effect.Common.amap a -> xs: Prims.list Steel.Effect.Common.atom -> FStar.Pervasives.Lemma (ensures EQ?.eq eq (Steel.Effect.Common.xsdenote eq m am xs) (Steel.Effect.Common.xsdenote eq m am (Steel.Effect.Common.sort xs))) (decreases FStar.List.Tot.Base.length xs)
FStar.Pervasives.Lemma
[ "lemma", "" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "Steel.Effect.Common.amap", "Prims.list", "Steel.Effect.Common.atom", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__reflexivity", "Steel.Effect.Common.xsdenote", "Prims.Nil", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "Steel.Effect.Common.sort", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__transitivity", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult", "Steel.Effect.Common.select", "Prims.Cons", "Steel.Effect.Common.lemma_xsdenote_aux", "Prims._assert", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__congruence", "Steel.Effect.Common.partition_equiv", "Steel.Effect.Common.sort_correct_aux", "FStar.List.Tot.Base.partition_length", "FStar.List.Tot.Base.bool_of_compare", "Prims.int", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__associativity", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__commutativity", "Steel.Effect.Common.flatten_correct_aux", "FStar.Pervasives.Native.tuple2", "FStar.List.Tot.Base.partition", "FStar.List.Tot.Base.compare_of_bool", "Prims.op_LessThan", "Prims.l_True", "Prims.squash", "Prims.eq2", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Steel.Effect.Common.sortWith_ext", "Steel.Effect.Common.my_compare_of_bool", "Steel.Effect.Common.permute", "FStar.List.Tot.Base.sortWith" ]
[ "recursion" ]
false
false
true
false
false
let rec sort_correct_aux (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (xs: list atom) : Lemma (requires True) (ensures CE.EQ?.eq eq (xsdenote eq m am xs) (xsdenote eq m am (sort xs))) (decreases (FStar.List.Tot.Base.length xs)) =
let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot :: q -> let sort0:permute = List.Tot.sortWith #int (List.Tot.compare_of_bool ( < )) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool ( < )) (List.Tot.compare_of_bool ( < )) l in let open FStar.List.Tot.Base in let f: int -> int -> int = compare_of_bool ( < ) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot :: sort hi); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot :: sort hi)))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot :: sort hi)) (xsdenote eq m am (sort lo)) (CM?.mult m (select pivot am) (xsdenote eq m am (sort hi))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot :: sort hi))) (CM?.mult m (xsdenote eq m am (sort lo)) (CM?.mult m (select pivot am) (xsdenote eq m am (sort hi)))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (CM?.mult m (xsdenote eq m am (sort lo)) (CM?.mult m (select pivot am) (xsdenote eq m am (sort hi))))); CM?.commutativity m (xsdenote eq m am (sort lo)) (CM?.mult m (select pivot am) (xsdenote eq m am (sort hi))); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am (sort lo)) (CM?.mult m (select pivot am) (xsdenote eq m am (sort hi)))) (CM?.mult m (CM?.mult m (select pivot am) (xsdenote eq m am (sort hi))) (xsdenote eq m am (sort lo))) (CM?.mult m (select pivot am) (CM?.mult m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (CM?.mult m (xsdenote eq m am (sort lo)) (CM?.mult m (select pivot am) (xsdenote eq m am (sort hi)))) (CM?.mult m (select pivot am) (CM?.mult m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (CM?.mult m (select pivot am) (CM?.mult m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo))))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (CM?.mult m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo))) (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo))); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (CM?.mult m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo))) (select pivot am) (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (CM?.mult m (select pivot am) (CM?.mult m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)))) (CM?.mult m (select pivot am) (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (CM?.mult m (select pivot am) (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (CM?.mult m (select pivot am) (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo))) (CM?.mult m (select pivot am) (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (CM?.mult m (select pivot am) (xsdenote eq m am q)) ); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot :: q)) (CM?.mult m (select pivot am) (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (CM?.mult m (select pivot am) (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.partition_equiv
val partition_equiv (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (pivot: atom) (q: list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool ( < )) pivot) q in CE.EQ?.eq eq (CE.CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (xsdenote eq m am q))
val partition_equiv (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (pivot: atom) (q: list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool ( < )) pivot) q in CE.EQ?.eq eq (CE.CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (xsdenote eq m am q))
let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 12, "end_line": 1411, "start_col": 0, "start_line": 1293 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl))
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 1, "initial_ifuel": 1, "max_fuel": 1, "max_ifuel": 1, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
eq: FStar.Algebra.CommMonoid.Equiv.equiv a -> m: FStar.Algebra.CommMonoid.Equiv.cm a eq -> am: Steel.Effect.Common.amap a -> pivot: Steel.Effect.Common.atom -> q: Prims.list Steel.Effect.Common.atom -> FStar.Pervasives.Lemma (ensures (let _ = FStar.List.Tot.Base.partition (FStar.List.Tot.Base.bool_of_compare (FStar.List.Tot.Base.compare_of_bool Prims.op_LessThan) pivot) q in (let FStar.Pervasives.Native.Mktuple2 #_ #_ hi lo = _ in EQ?.eq eq (CM?.mult m (Steel.Effect.Common.xsdenote eq m am hi) (Steel.Effect.Common.xsdenote eq m am lo)) (Steel.Effect.Common.xsdenote eq m am q)) <: Type0))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.Algebra.CommMonoid.Equiv.equiv", "FStar.Algebra.CommMonoid.Equiv.cm", "Steel.Effect.Common.amap", "Steel.Effect.Common.atom", "Prims.list", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__identity", "Steel.Effect.Common.xsdenote", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__transitivity", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult", "Steel.Effect.Common.select", "Prims.Cons", "Prims.unit", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__symmetry", "Steel.Effect.Common.lemma_xsdenote_aux", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__congruence", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__reflexivity", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__associativity", "Prims._assert", "Prims.l_and", "Prims.eq2", "Prims.bool", "FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__commutativity", "FStar.Algebra.CommMonoid.Equiv.__proj__EQ__item__eq", "Steel.Effect.Common.partition_equiv", "FStar.Pervasives.Native.tuple2", "FStar.List.Tot.Base.partition", "Prims.int", "FStar.List.Tot.Base.bool_of_compare", "FStar.List.Tot.Base.compare_of_bool", "Prims.op_LessThan", "Prims.l_True", "Prims.squash", "Prims.Nil", "FStar.Pervasives.pattern" ]
[ "recursion" ]
false
false
true
false
false
let rec partition_equiv (#a: Type) (eq: CE.equiv a) (m: CE.cm a eq) (am: amap a) (pivot: atom) (q: list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool ( < )) pivot) q in CE.EQ?.eq eq (CE.CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (xsdenote eq m am q)) =
let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool ( < )) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd :: tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (CM?.mult m (xsdenote eq m am l1) (xsdenote eq m am l2)) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then (assert (hi == hd :: l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (CM?.mult m (select hd am) (xsdenote eq m am l1)) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (CM?.mult m (CM?.mult m (select hd am) (xsdenote eq m am l1)) (xsdenote eq m am l2)) (CM?.mult m (select hd am) (CM?.mult m (xsdenote eq m am l1) (xsdenote eq m am l2))); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (CM?.mult m (xsdenote eq m am l1) (xsdenote eq m am l2)) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (CM?.mult m (select hd am) (CM?.mult m (xsdenote eq m am l1) (xsdenote eq m am l2))) (CM?.mult m (select hd am) (xsdenote eq m am tl)); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd :: tl)) (CM?.mult m (select hd am) (xsdenote eq m am tl)); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (CM?.mult m (select hd am) (xsdenote eq m am tl)) (xsdenote eq m am (hd :: tl))) else (assert (hi == l1 /\ lo == hd :: l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (CM?.mult m (select hd am) (xsdenote eq m am l2)); CM?.commutativity m (xsdenote eq m am l1) (CM?.mult m (select hd am) (xsdenote eq m am l2)); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (CM?.mult m (xsdenote eq m am l1) (CM?.mult m (select hd am) (xsdenote eq m am l2))) (CM?.mult m (CM?.mult m (select hd am) (xsdenote eq m am l2)) (xsdenote eq m am l1)); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (CM?.mult m (CM?.mult m (select hd am) (xsdenote eq m am l2)) (xsdenote eq m am l1)) (CM?.mult m (select hd am) (CM?.mult m (xsdenote eq m am l2) (xsdenote eq m am l1))); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (CM?.mult m (xsdenote eq m am l2) (xsdenote eq m am l1)) (select hd am) (CM?.mult m (xsdenote eq m am l1) (xsdenote eq m am l2)); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (CM?.mult m (select hd am) (CM?.mult m (xsdenote eq m am l2) (xsdenote eq m am l1))) (CM?.mult m (select hd am) (CM?.mult m (xsdenote eq m am l1) (xsdenote eq m am l2))); CM?.congruence m (select hd am) (CM?.mult m (xsdenote eq m am l1) (xsdenote eq m am l2)) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (CM?.mult m (select hd am) (CM?.mult m (xsdenote eq m am l1) (xsdenote eq m am l2))) (CM?.mult m (select hd am) (xsdenote eq m am tl)); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd :: tl)) (CM?.mult m (select hd am) (xsdenote eq m am tl)); EQ?.transitivity eq (CM?.mult m (xsdenote eq m am hi) (xsdenote eq m am lo)) (CM?.mult m (select hd am) (xsdenote eq m am tl)) (xsdenote eq m am (hd :: tl)))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.extract_cbs_forall_dep_contexts
val extract_cbs_forall_dep_contexts : t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Pervasives.Native.option (_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit))
let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 40, "end_line": 2472, "start_col": 0, "start_line": 2466 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Pervasives.Native.option (_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit))
FStar.Tactics.Effect.Tac
[]
[]
[ "Steel.Effect.Common.extract_contexts" ]
[]
false
true
false
false
false
let extract_cbs_forall_dep_contexts =
extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.slterm_nbr_uvars_argv
val slterm_nbr_uvars_argv (args: list argv) : Tac int
val slterm_nbr_uvars_argv (args: list argv) : Tac int
let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 59, "end_line": 2124, "start_col": 0, "start_line": 2110 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac Prims.int
FStar.Tactics.Effect.Tac
[]
[ "slterm_nbr_uvars", "slterm_nbr_uvars_argv" ]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Tactics.Util.fold_left", "Prims.int", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.NamedView.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.op_Addition", "Steel.Effect.Common.slterm_nbr_uvars" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec slterm_nbr_uvars_argv (args: list argv) : Tac int =
fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args
false
Steel.Effect.Common.fsti
Steel.Effect.Common.try_open_existentials_forall_dep
val try_open_existentials_forall_dep: Prims.unit -> Tac bool
val try_open_existentials_forall_dep: Prims.unit -> Tac bool
let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false )
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 3, "end_line": 2524, "start_col": 0, "start_line": 2517 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "FStar.Tactics.V2.Derived.focus", "Prims.bool", "FStar.Tactics.V2.Derived.try_with", "Steel.Effect.Common.open_existentials_forall_dep", "Prims.exn" ]
[]
false
true
false
false
false
let try_open_existentials_forall_dep () : Tac bool =
focus (fun _ -> try (open_existentials_forall_dep (); true) with | _ -> false)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_can_be_split
val solve_can_be_split (args: list argv) : Tac bool
val solve_can_be_split (args: list argv) : Tac bool
let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 14, "end_line": 2382, "start_col": 0, "start_line": 2345 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Tactics.V2.Derived.try_with", "Prims.bool", "Prims.unit", "FStar.Tactics.V2.Derived.focus", "FStar.Tactics.V2.Derived.or_else", "FStar.Tactics.V2.Derived.apply_lemma", "Steel.Effect.Common.canon'", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "FStar.Pervasives.delta_attr", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "Prims.op_Equality", "Prims.int", "Steel.Effect.Common.dismiss_slprops", "Prims.exn", "Steel.Effect.Common.solve_can_be_split", "Steel.Effect.Common.try_open_existentials", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "Steel.Effect.Common.unfold_guard", "Steel.Effect.Common.slterm_nbr_uvars" ]
[ "recursion" ]
false
true
false
false
false
let rec solve_can_be_split (args: list argv) : Tac bool =
match args with | [t1, _ ; t2, _] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then (let open FStar.Algebra.CommMonoid.Equiv in try (focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [ delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd ]; delta_attr [`%__reduce__]; primops; iota; zeta ]; canon' false (`true_p) (`true_p))); true) with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args else false) else false | _ -> false
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_can_be_split_dep
val solve_can_be_split_dep (args: list argv) : Tac bool
val solve_can_be_split_dep (args: list argv) : Tac bool
let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 43, "end_line": 2422, "start_col": 0, "start_line": 2385 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.bool", "Prims.unit", "FStar.Tactics.V2.Derived.focus", "FStar.Tactics.V2.Derived.or_else", "FStar.Tactics.V2.Derived.apply_lemma", "Prims.op_Negation", "FStar.Tactics.V2.Derived.fail", "FStar.Tactics.V2.Derived.unify", "Steel.Effect.Common.canon'", "FStar.Tactics.V2.SyntaxCoercions.binding_to_term", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "FStar.Pervasives.delta_attr", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Tactics.V2.Derived.flip", "Prims.op_AmpAmp", "Prims.op_disEquality", "Prims.int", "Prims.op_Equality", "Steel.Effect.Common.dismiss_slprops", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Logic.implies_intro", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "Steel.Effect.Common.unfold_guard", "Steel.Effect.Common.slterm_nbr_uvars" ]
[]
false
true
false
false
false
let solve_can_be_split_dep (args: list argv) : Tac bool =
match args with | [p, _ ; t1, _ ; t2, _] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then (let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [ delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd ]; delta_attr [`%__reduce__]; primops; iota; zeta ]; canon' true p (binding_to_term p_bind))); true) else false | _ -> fail "ill-formed can_be_split_dep"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.bring_last_goal_on_top
val bring_last_goal_on_top : _: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 30, "end_line": 2234, "start_col": 0, "start_line": 2232 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Steel.Effect.Common.bring_last_goal_on_top'", "Prims.Nil", "FStar.Stubs.Tactics.Types.goal", "Prims.list", "FStar.Tactics.V2.Derived.goals" ]
[]
false
true
false
false
false
let bring_last_goal_on_top () =
let g = goals () in bring_last_goal_on_top' [] g
false
Steel.Closure.fst
Steel.Closure.next
val next (r: ref int) (prev: erased int) : SteelT (y: int{y == prev + 1}) (repr r prev) (repr r)
val next (r: ref int) (prev: erased int) : SteelT (y: int{y == prev + 1}) (repr r prev) (repr r)
let next (r:ref int) (prev:erased int) : SteelT (y:int{y == prev + 1}) (repr r prev) (repr r) = let v = read_pt r in let (x:int { x == prev + 1 }) = v + 1 in write_pt r x; x
{ "file_name": "lib/steel/Steel.Closure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 5, "end_line": 35, "start_col": 0, "start_line": 30 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Closure open Steel.Memory open Steel.Effect.Atomic open Steel.Effect open Steel.Reference open Steel.FractionalPermission [@@__reduce__] let repr (r:ref int) (x:int) = pts_to r full_perm (hide x) let ctr (r:ref int) = prev:erased int -> SteelT (y:int{y == prev + 1}) (repr r prev) (repr r)
{ "checked_file": "/", "dependencies": [ "Steel.Reference.fsti.checked", "Steel.Memory.fsti.checked", "Steel.FractionalPermission.fst.checked", "Steel.Effect.Atomic.fsti.checked", "Steel.Effect.fsti.checked", "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": true, "source_file": "Steel.Closure.fst" }
[ { "abbrev": false, "full_module": "Steel.FractionalPermission", "short_module": null }, { "abbrev": false, "full_module": "Steel.Reference", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect.Atomic", "short_module": null }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel", "short_module": null }, { "abbrev": false, "full_module": "Steel", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
r: Steel.Reference.ref Prims.int -> prev: FStar.Ghost.erased Prims.int -> Steel.Effect.SteelT (y: Prims.int{y == FStar.Ghost.reveal prev + 1})
Steel.Effect.SteelT
[]
[]
[ "Steel.Reference.ref", "Prims.int", "FStar.Ghost.erased", "Prims.eq2", "Prims.op_Addition", "FStar.Ghost.reveal", "Prims.unit", "Steel.Reference.write_pt", "FStar.Ghost.hide", "Steel.Reference.read_pt", "Steel.FractionalPermission.full_perm", "Steel.Closure.repr" ]
[]
false
true
false
false
false
let next (r: ref int) (prev: erased int) : SteelT (y: int{y == prev + 1}) (repr r prev) (repr r) =
let v = read_pt r in let x:x: int{x == prev + 1} = v + 1 in write_pt r x; x
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_can_be_split_forall_dep
val solve_can_be_split_forall_dep (args: list argv) : Tac bool
val solve_can_be_split_forall_dep (args: list argv) : Tac bool
let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 69, "end_line": 2577, "start_col": 0, "start_line": 2527 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false )
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Tactics.V2.Derived.try_with", "Prims.bool", "Prims.unit", "FStar.Tactics.V2.Derived.focus", "FStar.Tactics.V2.Derived.or_else", "FStar.Tactics.V2.Derived.apply_lemma", "Prims.op_Negation", "FStar.Tactics.V2.Derived.fail", "FStar.Tactics.V2.Derived.unify", "Steel.Effect.Common.canon'", "FStar.Tactics.V2.SyntaxCoercions.binding_to_term", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "FStar.Pervasives.delta_attr", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Tactics.V2.Derived.flip", "Prims.op_AmpAmp", "Prims.op_disEquality", "Prims.int", "Prims.op_Equality", "FStar.Tactics.NamedView.term", "FStar.Tactics.V2.Derived.norm_term", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Logic.implies_intro", "FStar.Reflection.V2.Derived.mk_app", "FStar.Pervasives.Native.Mktuple2", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "FStar.Tactics.V2.Logic.forall_intro", "Prims.exn", "Steel.Effect.Common.solve_can_be_split_forall_dep", "Steel.Effect.Common.try_open_existentials_forall_dep", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "Steel.Effect.Common.unfold_guard", "Steel.Effect.Common.slterm_nbr_uvars" ]
[ "recursion" ]
false
true
false
false
false
let rec solve_can_be_split_forall_dep (args: list argv) : Tac bool =
match args with | [_ ; pr, _ ; t1, _ ; t2, _] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then (let open FStar.Algebra.CommMonoid.Equiv in try (focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip ()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [ delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd ]; delta_attr [`%__reduce__]; primops; iota; zeta ]; canon' true pr (binding_to_term p_bind))); true) with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args else fail msg | _ -> fail "Unexpected exception in framing tactic") else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_can_be_split_forall
val solve_can_be_split_forall (args: list argv) : Tac bool
val solve_can_be_split_forall (args: list argv) : Tac bool
let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 65, "end_line": 2460, "start_col": 0, "start_line": 2429 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp))
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.bool", "Prims.unit", "FStar.Tactics.V2.Derived.focus", "FStar.Tactics.V2.Derived.or_else", "FStar.Tactics.V2.Derived.apply_lemma", "Steel.Effect.Common.canon'", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "FStar.Pervasives.delta_attr", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Tactics.V2.Derived.flip", "Prims.op_AmpAmp", "Prims.op_disEquality", "Prims.int", "Prims.op_Equality", "Steel.Effect.Common.dismiss_slprops", "FStar.Pervasives.ignore", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Logic.forall_intro", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "Steel.Effect.Common.unfold_guard", "Steel.Effect.Common.slterm_nbr_uvars", "FStar.Tactics.V2.Derived.fail" ]
[]
false
true
false
false
false
let solve_can_be_split_forall (args: list argv) : Tac bool =
match args with | [_ ; t1, _ ; t2, _] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then (let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro ()); apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [ delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd ]; delta_attr [`%__reduce__]; primops; iota; zeta ]; canon' false (`true_p) (`true_p))); true) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.quote_exp
val quote_exp (e: exp) : term
val quote_exp (e: exp) : term
let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt))
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 30, "end_line": 1674, "start_col": 0, "start_line": 1669 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) )
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
e: Steel.Effect.Common.exp -> FStar.Tactics.NamedView.term
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.exp", "FStar.Stubs.Reflection.Types.term", "Steel.Effect.Common.quote_exp", "Steel.Effect.Common.atom", "FStar.Tactics.NamedView.term", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Const", "FStar.Stubs.Reflection.V2.Data.C_Int" ]
[ "recursion" ]
false
false
false
true
false
let rec quote_exp (e: exp) : term =
match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_equiv
val solve_equiv (args: list argv) : Tac bool
val solve_equiv (args: list argv) : Tac bool
let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 51, "end_line": 2647, "start_col": 0, "start_line": 2617 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.bool", "Prims.unit", "FStar.Tactics.V2.Derived.focus", "FStar.Tactics.V2.Derived.or_else", "FStar.Tactics.V2.Derived.apply_lemma", "Steel.Effect.Common.canon'", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "FStar.Pervasives.delta_attr", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Tactics.V2.Derived.flip", "Prims.op_AmpAmp", "Prims.op_disEquality", "Prims.int", "Prims.op_Equality", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "Steel.Effect.Common.unfold_guard", "Steel.Effect.Common.slterm_nbr_uvars", "FStar.Tactics.V2.Derived.fail" ]
[]
false
true
false
false
false
let solve_equiv (args: list argv) : Tac bool =
match args with | [t1, _ ; t2, _] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then (let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [ delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd ]; delta_attr [`%__reduce__]; primops; iota; zeta ]; canon' false (`true_p) (`true_p))); true) else false | _ -> fail "Ill-formed equiv, should not happen"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_equiv_forall
val solve_equiv_forall (args: list argv) : Tac bool
val solve_equiv_forall (args: list argv) : Tac bool
let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 58, "end_line": 2614, "start_col": 0, "start_line": 2580 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.bool", "Prims.unit", "FStar.Tactics.V2.Derived.focus", "FStar.Stubs.Tactics.Types.goal", "FStar.Tactics.V2.Derived.or_else", "FStar.Tactics.V2.Derived.apply_lemma", "Steel.Effect.Common.canon'", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "FStar.Pervasives.delta_attr", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Tactics.V2.Derived.flip", "Prims.op_AmpAmp", "Prims.op_disEquality", "Prims.int", "Prims.op_Equality", "FStar.Pervasives.ignore", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Logic.forall_intro", "Steel.Effect.Common.dismiss_slprops", "FStar.Tactics.V2.Derived.goals", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "Steel.Effect.Common.unfold_guard", "Steel.Effect.Common.slterm_nbr_uvars", "FStar.Tactics.V2.Derived.fail" ]
[]
false
true
false
false
false
let solve_equiv_forall (args: list argv) : Tac bool =
match args with | [_ ; t1, _ ; t2, _] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then (let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro ()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [ delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd ]; delta_attr [`%__reduce__]; primops; iota; zeta ]; canon' false (`true_p) (`true_p))); true) else false | _ -> fail "Ill-formed equiv_forall, should not happen"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.elim_and_l_squash
val elim_and_l_squash (#a #b #goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal)
val elim_and_l_squash (#a #b #goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal)
let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h))
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 47, "end_line": 1814, "start_col": 0, "start_line": 1809 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there")
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: a -> Prims.squash goal) -> h: a /\ b -> Prims.squash goal
Prims.Tot
[ "total" ]
[]
[ "Prims.squash", "Prims.l_and", "FStar.Squash.return_squash", "FStar.Squash.bind_squash" ]
[]
false
false
true
true
false
let elim_and_l_squash (#a #b #goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) =
let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.is_return_eq
val is_return_eq (l r: term) : Tac bool
val is_return_eq (l r: term) : Tac bool
let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 56, "end_line": 2693, "start_col": 0, "start_line": 2690 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: FStar.Tactics.NamedView.term -> r: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "Prims.op_BarBar", "FStar.Reflection.V2.Derived.is_fvar", "Prims.bool", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app" ]
[]
false
true
false
false
false
let is_return_eq (l r: term) : Tac bool =
let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.argv_uvars
val argv_uvars (args: list argv) : Tac (list int)
val argv_uvars (args: list argv) : Tac (list int)
let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t ()
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 6, "end_line": 2854, "start_col": 0, "start_line": 2828 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac (Prims.list Prims.int)
FStar.Tactics.Effect.Tac
[]
[ "vprop_term_uvars", "argv_uvars" ]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "Prims.int", "Prims.unit", "FStar.Tactics.Util.fold_left", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.NamedView.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.List.Tot.Base.append", "Steel.Effect.Common.vprop_term_uvars", "Prims.Nil" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec argv_uvars (args: list argv) : Tac (list int) =
let t: unit -> Tac (list int) = fold_left (fun (n: (unit -> Tac (list int))) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t) (fun _ -> []) args in t ()
false
Steel.Effect.Common.fsti
Steel.Effect.Common.goal_term_uvars
val goal_term_uvars (t: term) : Tac (list int)
val goal_term_uvars (t: term) : Tac (list int)
let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else []
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 6, "end_line": 2873, "start_col": 0, "start_line": 2863 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (Prims.list Prims.int)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Reflection.V2.Derived.is_fvar", "FStar.Stubs.Reflection.Types.term", "Steel.Effect.Common.simplify_list", "Prims.int", "Steel.Effect.Common.argv_uvars", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app", "Prims.Nil", "Prims.unit", "FStar.Stubs.Tactics.V2.Builtins.dump", "Prims.bool" ]
[]
false
true
false
false
false
let goal_term_uvars (t: term) : Tac (list int) =
let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else []
false
Steel.Effect.Common.fsti
Steel.Effect.Common.elim_and_r_squash
val elim_and_r_squash (#a #b #goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal)
val elim_and_r_squash (#a #b #goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal)
let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h))
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 47, "end_line": 1821, "start_col": 0, "start_line": 1816 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h))
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: b -> Prims.squash goal) -> h: a /\ b -> Prims.squash goal
Prims.Tot
[ "total" ]
[]
[ "Prims.squash", "Prims.l_and", "FStar.Squash.return_squash", "FStar.Squash.bind_squash" ]
[]
false
false
true
true
false
let elim_and_r_squash (#a #b #goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) =
let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h))
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_can_be_split_post
val solve_can_be_split_post (args: list argv) : Tac bool
val solve_can_be_split_post (args: list argv) : Tac bool
let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 44, "end_line": 2687, "start_col": 0, "start_line": 2650 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
args: Prims.list FStar.Stubs.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.bool", "Prims.unit", "FStar.Tactics.V2.Derived.focus", "FStar.Stubs.Tactics.Types.goal", "FStar.Tactics.V2.Derived.or_else", "FStar.Tactics.V2.Derived.apply_lemma", "Steel.Effect.Common.canon'", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "FStar.Pervasives.delta_attr", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Tactics.V2.Derived.flip", "Prims.op_AmpAmp", "Prims.op_disEquality", "Prims.int", "Prims.op_Equality", "FStar.Pervasives.ignore", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Logic.forall_intro", "Steel.Effect.Common.dismiss_slprops", "FStar.Tactics.V2.Derived.goals", "FStar.Tactics.V2.Derived._cur_goal", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "Steel.Effect.Common.unfold_guard", "Steel.Effect.Common.slterm_nbr_uvars", "FStar.Tactics.V2.Derived.fail" ]
[]
false
true
false
false
false
let solve_can_be_split_post (args: list argv) : Tac bool =
match args with | [_ ; _ ; t1, _ ; t2, _] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then (let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm []; let g = _cur_goal () in ignore (forall_intro ()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro ()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [ delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd ]; delta_attr [`%__reduce__]; primops; iota; zeta ]; canon' false (`true_p) (`true_p))); true) else false | _ -> fail "ill-formed can_be_split_post"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.vprop_term_uvars
val vprop_term_uvars (t: term) : Tac (list int)
val vprop_term_uvars (t: term) : Tac (list int)
let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t ()
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 6, "end_line": 2854, "start_col": 0, "start_line": 2828 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (Prims.list Prims.int)
FStar.Tactics.Effect.Tac
[]
[ "vprop_term_uvars", "argv_uvars" ]
[ "FStar.Tactics.NamedView.term", "Prims.nat", "FStar.Stubs.Reflection.Types.ctx_uvar_and_subst", "Prims.Cons", "Prims.int", "Prims.Nil", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "Steel.Effect.Common.is_star_or_unit", "Steel.Effect.Common.argv_uvars", "Prims.bool", "Steel.Effect.Common.vprop_term_uvars", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app", "FStar.Tactics.NamedView.binder", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.NamedView.term_view", "Prims.b2t", "FStar.Tactics.NamedView.notAscription", "FStar.Tactics.V2.SyntaxHelpers.inspect_unascribe" ]
[ "mutual recursion" ]
false
true
false
false
false
let rec vprop_term_uvars (t: term) : Tac (list int) =
match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> []
false
Steel.Effect.Common.fsti
Steel.Effect.Common.compute_guarded_uvars
val compute_guarded_uvars: Prims.unit -> Tac (list int)
val compute_guarded_uvars: Prims.unit -> Tac (list int)
let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 31, "end_line": 2942, "start_col": 0, "start_line": 2939 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac (Prims.list Prims.int)
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Steel.Effect.Common.compute_guarded_uvars3", "Prims.list", "Prims.int", "Steel.Effect.Common.compute_guarded_uvars1", "Prims.Nil", "FStar.Stubs.Tactics.Types.goal", "FStar.Tactics.V2.Derived.goals" ]
[]
false
true
false
false
false
let compute_guarded_uvars () : Tac (list int) =
let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g
false
Steel.Effect.Common.fsti
Steel.Effect.Common.simplify_list
val simplify_list (l: list int) : Tot (list int)
val simplify_list (l: list int) : Tot (list int)
let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 78, "end_line": 2861, "start_col": 0, "start_line": 2860 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Prims.list Prims.int -> Prims.list Prims.int
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Prims.int", "Steel.Effect.Common.remove_dups_from_sorted", "FStar.List.Tot.Base.sortWith", "FStar.List.Tot.Base.compare_of_bool", "Prims.op_LessThan" ]
[]
false
false
false
true
false
let simplify_list (l: list int) : Tot (list int) =
remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool ( < )) l)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.lookup_by_term_attr'
val lookup_by_term_attr' (attr: term) (e: env) (found l: list fv) : Tac (list fv)
val lookup_by_term_attr' (attr: term) (e: env) (found l: list fv) : Tac (list fv)
let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 7, "end_line": 2219, "start_col": 0, "start_line": 2204 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
attr: FStar.Tactics.NamedView.term -> e: FStar.Stubs.Reflection.Types.env -> found: Prims.list FStar.Stubs.Reflection.Types.fv -> l: Prims.list FStar.Stubs.Reflection.Types.fv -> FStar.Tactics.Effect.Tac (Prims.list FStar.Stubs.Reflection.Types.fv)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "FStar.Stubs.Reflection.Types.env", "Prims.list", "FStar.Stubs.Reflection.Types.fv", "FStar.List.Tot.Base.rev", "FStar.Stubs.Reflection.V2.Builtins.lookup_typ", "Steel.Effect.Common.lookup_by_term_attr'", "FStar.Stubs.Reflection.Types.sigelt", "Prims.Cons", "Prims.bool", "Steel.Effect.Common.term_mem", "FStar.Stubs.Reflection.V2.Builtins.sigelt_attrs", "FStar.Stubs.Reflection.Types.name", "FStar.Stubs.Reflection.V2.Builtins.inspect_fv" ]
[ "recursion" ]
false
true
false
false
false
let rec lookup_by_term_attr' (attr: term) (e: env) (found l: list fv) : Tac (list fv) =
match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` (sigelt_attrs se) then f :: found else found in lookup_by_term_attr' attr e found' q
false
Steel.Effect.Common.fsti
Steel.Effect.Common.term_mem
val term_mem (te: term) (l: list term) : Tac bool
val term_mem (te: term) (l: list term) : Tac bool
let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 55, "end_line": 2202, "start_col": 0, "start_line": 2198 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
te: FStar.Tactics.NamedView.term -> l: Prims.list FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "Prims.bool", "Steel.Effect.Common.term_mem", "FStar.Stubs.Tactics.V2.Builtins.term_eq_old" ]
[ "recursion" ]
false
true
false
false
false
let rec term_mem (te: term) (l: list term) : Tac bool =
match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q
false
Steel.Effect.Common.fsti
Steel.Effect.Common.goal_to_equiv
val goal_to_equiv (loc: string) : Tac unit
val goal_to_equiv (loc: string) : Tac unit
let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal")
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 42, "end_line": 2769, "start_col": 0, "start_line": 2741 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
loc: Prims.string -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.string", "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Reflection.V2.Derived.is_fvar", "FStar.Tactics.V2.Derived.apply_lemma", "Prims.unit", "Prims.bool", "FStar.Pervasives.ignore", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Logic.forall_intro", "Steel.Effect.Common.dismiss_slprops", "FStar.Tactics.V2.Derived.fail", "Prims.op_Hat", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app", "Prims.op_Negation", "FStar.Reflection.V2.Formula.formula", "FStar.Reflection.V2.Formula.term_as_formula'", "FStar.Stubs.Reflection.Types.typ", "FStar.Tactics.V2.Derived.cur_goal" ]
[]
false
true
false
false
false
let goal_to_equiv (loc: string) : Tac unit =
let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then (apply_lemma (`equiv_can_be_split)) else if hd `is_fvar` (`%can_be_split_forall) then (ignore (forall_intro ()); apply_lemma (`equiv_can_be_split)) else if hd `is_fvar` (`%equiv_forall) then (apply_lemma (`equiv_forall_elim); ignore (forall_intro ())) else if hd `is_fvar` (`%can_be_split_post) then (apply_lemma (`can_be_split_post_elim); dismiss_slprops (); ignore (forall_intro ()); ignore (forall_intro ())) else if hd `is_fvar` (`%can_be_split_dep) then (fail ("can_be_split_dep not supported in " ^ loc)) else if hd `is_fvar` (`%can_be_split_forall_dep) then (fail ("can_be_split_forall_dep not supported in " ^ loc)) else fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal")
false
Steel.Effect.Common.fsti
Steel.Effect.Common.typ_contains_req_ens
val typ_contains_req_ens (t: term) : Tac bool
val typ_contains_req_ens (t: term) : Tac bool
let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post]
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 73, "end_line": 2998, "start_col": 0, "start_line": 2996 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Reflection.V2.Derived.is_any_fvar", "Prims.Cons", "Prims.string", "Prims.Nil", "Prims.bool", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app" ]
[]
false
true
false
false
false
let typ_contains_req_ens (t: term) : Tac bool =
let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post]
false
Steel.Effect.Common.fsti
Steel.Effect.Common.canon_l_r
val canon_l_r (use_smt: bool) (carrier_t eq m pr pr_bind lhs rel rhs: term) : Tac unit
val canon_l_r (use_smt: bool) (carrier_t eq m pr pr_bind lhs rel rhs: term) : Tac unit
let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable ()
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 29, "end_line": 2078, "start_col": 0, "start_line": 1858 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal"
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
use_smt: Prims.bool -> carrier_t: FStar.Tactics.NamedView.term -> eq: FStar.Tactics.NamedView.term -> m: FStar.Tactics.NamedView.term -> pr: FStar.Tactics.NamedView.term -> pr_bind: FStar.Tactics.NamedView.term -> lhs: FStar.Tactics.NamedView.term -> rel: FStar.Tactics.NamedView.term -> rhs: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.bool", "FStar.Tactics.NamedView.term", "Steel.Effect.Common.exp", "Prims.list", "Steel.Effect.Common.amap", "Steel.Effect.Common.atom", "FStar.Tactics.V2.Derived.focus", "Prims.unit", "FStar.Tactics.V2.Derived.try_with", "FStar.Tactics.V2.Derived.apply_lemma", "Steel.Effect.Common.unify_pr_with_true", "FStar.Tactics.V2.Logic.split", "Prims.exn", "Prims.string", "FStar.Tactics.V2.Derived.fail", "Prims.op_Hat", "FStar.Tactics.Effect.raise", "Steel.Effect.Common.set_abduction_variable", "FStar.Stubs.Tactics.V2.Builtins.revert", "Steel.Effect.Common.close_equality_typ", "FStar.Tactics.V2.Derived.cur_goal", "FStar.Stubs.Reflection.Types.typ", "FStar.Stubs.Tactics.V2.Builtins.t_trefl", "FStar.Pervasives.ignore", "Prims.l_or", "Prims.b2t", "Prims.op_LessThan", "FStar.List.Tot.Base.length", "FStar.Pervasives.Native.tuple3", "FStar.Tactics.NamedView.namedv", "Prims.eq2", "Prims.int", "FStar.Tactics.Util.repeatn", "Steel.Effect.Common.dismiss_slprops", "FStar.Tactics.V2.Derived.exact", "FStar.Tactics.V2.SyntaxCoercions.binding_to_term", "FStar.Tactics.V2.Derived.apply", "FStar.Tactics.V2.Derived.trefl", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Pervasives.delta_only", "Prims.Nil", "Prims.op_Equality", "FStar.Stubs.Tactics.Types.goal", "FStar.Tactics.V2.Derived.goals", "FStar.Stubs.Reflection.Types.term", "Steel.Effect.Common.quote_atoms", "FStar.Tactics.V2.Derived.change_sq", "Steel.Effect.Common.quote_exp", "Steel.Effect.Common.convert_am", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Logic.implies_intro", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.snd", "FStar.Tactics.Util.fold_left", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Var", "FStar.Tactics.V2.SyntaxCoercions.binding_to_namedv", "FStar.Tactics.V2.Logic.forall_intro", "FStar.Tactics.Util.fold_right", "FStar.Stubs.Reflection.Types.binder", "FStar.Reflection.V2.Derived.mk_app", "FStar.Tactics.NamedView.Tv_FVar", "FStar.Stubs.Reflection.V2.Builtins.pack_fv", "FStar.Reflection.Const.forall_qn", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "FStar.Tactics.NamedView.Tv_Abs", "FStar.Tactics.NamedView.close_term", "FStar.Tactics.NamedView.binder", "FStar.Tactics.NamedView.Mkbinder", "FStar.Stubs.Reflection.V2.Data.__proj__Mknamedv_view__item__uniq", "FStar.Stubs.Reflection.V2.Data.__proj__Mknamedv_view__item__ppname", "FStar.Tactics.NamedView.inspect_namedv", "FStar.Reflection.Const.imp_qn", "Steel.Effect.Common.xsdenote_gen", "Steel.Effect.Common.mdenote_gen", "FStar.Tactics.Util.map", "FStar.Tactics.Util.mapi", "Prims.nat", "FStar.Pervasives.Native.Mktuple3", "FStar.Tactics.V2.Derived.fresh_namedv_named", "Prims.string_of_int", "FStar.Pervasives.Native.fst", "FStar.Pervasives.Native.tuple4", "Steel.Effect.Common.Result", "Steel.Effect.Common.equivalent_lists", "Steel.Effect.Common.flatten", "Steel.Effect.Common.reification", "Steel.Effect.Common.const", "FStar.Tactics.V2.Derived.norm_term", "FStar.Pervasives.delta" ]
[]
false
true
false
false
false
let canon_l_r (use_smt: bool) (carrier_t eq m pr pr_bind lhs rel rhs: term) : Tac unit =
let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in let r1_raw, ts, am = reification eq m [] am lhs in let r2_raw, _, am = reification eq m ts am rhs in let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in let am_bv:list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term:amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e: exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l: list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in let mk_rel (l r: term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in apply_lemma (`cut (`#aux_goal)); split (); focus (fun _ -> let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v)) :: am) [] am_bv, snd am in let b = implies_intro () in let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (CE.EQ?.eq (`#eq) (mdenote (`#eq) (`#m) (`#am) (`#r1)) (mdenote (`#eq) (`#m) (`#am) (`#r2))))); apply_lemma (`normal_elim); apply (`monoid_reflect); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else (norm [ primops; iota; zeta; delta_only [ `%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star ] ]; split (); split (); trefl (); trefl (); apply (`FStar.Squash.return_squash); exact (binding_to_term b))); dismiss_slprops (); ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); apply_lemma (`modus_ponens); match uvar_terms with | [] -> focus (fun _ -> try (apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; apply_lemma (`solve_implies_true)) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e) | l -> if emp_frame then (apply_lemma (`identity_left_smt (`#eq) (`#m))) else (apply_lemma (`smt_reflexivity (`#eq))); t_trefl true; close_equality_typ (cur_goal ()); revert (); set_abduction_variable ()
false
Steel.Effect.Common.fsti
Steel.Effect.Common.squash_and
val squash_and (p: _) (x: squash (p /\ True)) : (p /\ True)
val squash_and (p: _) (x: squash (p /\ True)) : (p /\ True)
let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 3, "end_line": 3121, "start_col": 0, "start_line": 3119 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' []
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: Prims.logical -> x: Prims.squash (p /\ Prims.l_True) -> p /\ Prims.l_True
Prims.Tot
[ "total" ]
[]
[ "Prims.logical", "Prims.squash", "Prims.l_and", "Prims.l_True", "Prims.pair", "FStar.Squash.join_squash" ]
[]
false
false
false
false
false
let squash_and p (x: squash (p /\ True)) : (p /\ True) =
let x:squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x
false
Steel.Effect.Common.fsti
Steel.Effect.Common.print_goal
val print_goal (g: goal) : Tac string
val print_goal (g: goal) : Tac string
let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 18, "end_line": 3066, "start_col": 0, "start_line": 3064 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
g: FStar.Stubs.Tactics.Types.goal -> FStar.Tactics.Effect.Tac Prims.string
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Stubs.Tactics.Types.goal", "FStar.Stubs.Tactics.V2.Builtins.term_to_string", "Prims.string", "FStar.Stubs.Reflection.Types.typ", "FStar.Stubs.Tactics.Types.goal_type" ]
[]
false
true
false
false
false
let print_goal (g: goal) : Tac string =
let t = goal_type g in term_to_string t
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_or_delay
val solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool
val solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool
let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 14, "end_line": 2822, "start_col": 0, "start_line": 2785 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q'
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
dict: Prims.list (FStar.Tactics.NamedView.term * (_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.bool)) -> FStar.Tactics.Effect.Tac Prims.bool
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.NamedView.term", "Prims.unit", "Prims.bool", "FStar.Reflection.V2.Derived.is_fvar", "FStar.Stubs.Reflection.V2.Data.argv", "Steel.Effect.Common.solve_can_be_split", "Steel.Effect.Common.solve_can_be_split_forall", "Steel.Effect.Common.solve_equiv_forall", "Steel.Effect.Common.solve_can_be_split_post", "Steel.Effect.Common.solve_equiv", "Steel.Effect.Common.solve_can_be_split_dep", "Steel.Effect.Common.solve_can_be_split_forall_dep", "FStar.Tactics.V2.Derived.try_with", "FStar.Tactics.V2.Derived.first", "FStar.List.Tot.Base.map", "Prims.exn", "FStar.Tactics.V2.Derived.smt", "Prims.op_Equality", "Prims.int", "FStar.List.Tot.Base.length", "FStar.Stubs.Tactics.V2.Builtins.free_uvars", "FStar.Tactics.V2.Derived.focus", "Steel.Effect.Common.term_dict_assoc", "FStar.Tactics.V2.SyntaxHelpers.collect_app", "FStar.Pervasives.Native.option", "FStar.Stubs.Reflection.Types.typ", "Prims.op_BarBar", "FStar.Tactics.V2.Derived.trefl", "Prims.nat", "FStar.Reflection.V2.Formula.formula", "FStar.Reflection.V2.Formula.term_as_formula'", "FStar.Tactics.V2.Derived.cur_goal", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Nil", "FStar.Pervasives.norm_step" ]
[]
false
true
false
false
false
let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool =
norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: (unit -> Tac bool)) () : Tac bool = focus tac in try first (List.Tot.map run_tac candidates) with | _ -> if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false else false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false
false
Steel.Effect.Common.fsti
Steel.Effect.Common.init_resolve_tac
val init_resolve_tac: Prims.unit -> Tac unit
val init_resolve_tac: Prims.unit -> Tac unit
let init_resolve_tac () : Tac unit = init_resolve_tac' []
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 57, "end_line": 3116, "start_col": 0, "start_line": 3116 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Steel.Effect.Common.init_resolve_tac'", "Prims.Nil", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.NamedView.term", "Prims.bool" ]
[]
false
true
false
false
false
let init_resolve_tac () : Tac unit =
init_resolve_tac' []
false
Steel.Effect.Common.fsti
Steel.Effect.Common.vc_norm
val vc_norm: Prims.unit -> Tac unit
val vc_norm: Prims.unit -> Tac unit
let vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> norm normal_steps; trefl())
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 88, "end_line": 3174, "start_col": 0, "start_line": 3174 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' [] (* AF: There probably is a simpler way to get from p to squash p in a tactic, so that we can use apply_lemma *) let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x /// Calling into the framing tactic to ensure that the vprop whose selector we are trying to access is in the context [@@plugin] let selector_tactic () : Tac unit = apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p) /// Specific tactic used during the SteelAtomicBase and SteelBase effect definitions: /// This allows us to write more complex if_then_else combinators, while proving them /// sound with respect to subcomp [@@ resolve_implicits; ite_attr] let ite_soundness_tac () : Tac unit = let slgs, loggoals = filter_goals (goals ()) in set_goals slgs; solve_indirection_eqs (List.Tot.length slgs); // This is the actual subcomp goal. We can only solve it // once all uvars are solved let subcomp_goal = _cur_goal () in match goals () with | [] -> fail "should not happen" | _::tl -> set_goals tl; or_else (fun _ -> apply_lemma (`equiv_forall_refl)) assumption; or_else (fun _ -> or_else (fun _ -> apply_lemma (`can_be_split_dep_refl)) (fun _ -> apply_lemma (`can_be_split_refl)) // Different formalism in Steel.ST ) assumption; // Discharging the maybe_emp by SMT smt (); // Now propagating all equalities for the requires/ensures set_goals loggoals; resolve_tac_logical []; // Now taking care of the actual subcomp VC set_goals [subcomp_goal]; norm []; smt () /// Normalization step for VC generation, used in Steel and SteelAtomic subcomps /// This tactic is executed after frame inference, and just before sending the query to the SMT
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "FStar.Stubs.Tactics.V2.Builtins.with_compat_pre_core", "FStar.Tactics.V2.Derived.trefl", "FStar.Stubs.Tactics.V2.Builtins.norm", "Steel.Effect.Common.normal_steps" ]
[]
false
true
false
false
false
let vc_norm () : Tac unit =
with_compat_pre_core 0 (fun _ -> norm normal_steps; trefl ())
false
Steel.Effect.Common.fsti
Steel.Effect.Common.name_of_inv
val name_of_inv (#p: vprop) (i: inv p) : GTot iname
val name_of_inv (#p: vprop) (i: inv p) : GTot iname
let name_of_inv (#p:vprop) (i:inv p) : GTot iname = Mem.name_of_inv i
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 69, "end_line": 3203, "start_col": 0, "start_line": 3203 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' [] (* AF: There probably is a simpler way to get from p to squash p in a tactic, so that we can use apply_lemma *) let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x /// Calling into the framing tactic to ensure that the vprop whose selector we are trying to access is in the context [@@plugin] let selector_tactic () : Tac unit = apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p) /// Specific tactic used during the SteelAtomicBase and SteelBase effect definitions: /// This allows us to write more complex if_then_else combinators, while proving them /// sound with respect to subcomp [@@ resolve_implicits; ite_attr] let ite_soundness_tac () : Tac unit = let slgs, loggoals = filter_goals (goals ()) in set_goals slgs; solve_indirection_eqs (List.Tot.length slgs); // This is the actual subcomp goal. We can only solve it // once all uvars are solved let subcomp_goal = _cur_goal () in match goals () with | [] -> fail "should not happen" | _::tl -> set_goals tl; or_else (fun _ -> apply_lemma (`equiv_forall_refl)) assumption; or_else (fun _ -> or_else (fun _ -> apply_lemma (`can_be_split_dep_refl)) (fun _ -> apply_lemma (`can_be_split_refl)) // Different formalism in Steel.ST ) assumption; // Discharging the maybe_emp by SMT smt (); // Now propagating all equalities for the requires/ensures set_goals loggoals; resolve_tac_logical []; // Now taking care of the actual subcomp VC set_goals [subcomp_goal]; norm []; smt () /// Normalization step for VC generation, used in Steel and SteelAtomic subcomps /// This tactic is executed after frame inference, and just before sending the query to the SMT /// As such, it is a good place to add debugging features to inspect SMT queries when needed let vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> norm normal_steps; trefl()) //////////////////////////////////////////////////////////////////////////////// //Common datatypes for the atomic & ghost effects //////////////////////////////////////////////////////////////////////////////// /// A datatype indicating whether a computation is ghost (unobservable) or not type observability : eqtype = | Observable | Unobservable (* Helpers to handle observability inside atomic computations *) unfold let obs_at_most_one (o1 o2:observability) = o1=Unobservable || o2=Unobservable unfold let join_obs (o1:observability) (o2:observability) = if o1 = Observable || o2 = Observable then Observable else Unobservable (* Lifting invariants to vprops *) /// [i : inv p] is an invariant whose content is [p] inline_for_extraction let inv (p:vprop) : Type0 = Mem.inv (hp_of p)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
i: Steel.Effect.Common.inv p -> Prims.GTot Steel.Memory.iname
Prims.GTot
[ "sometrivial" ]
[]
[ "Steel.Effect.Common.vprop", "Steel.Effect.Common.inv", "Steel.Memory.name_of_inv", "Steel.Effect.Common.hp_of", "Steel.Memory.iname" ]
[]
false
false
false
false
false
let name_of_inv (#p: vprop) (i: inv p) : GTot iname =
Mem.name_of_inv i
false
Steel.Effect.Common.fsti
Steel.Effect.Common.obs_at_most_one
val obs_at_most_one : o1: Steel.Effect.Common.observability -> o2: Steel.Effect.Common.observability -> Prims.bool
let obs_at_most_one (o1 o2:observability) = o1=Unobservable || o2=Unobservable
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 36, "end_line": 3189, "start_col": 0, "start_line": 3188 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' [] (* AF: There probably is a simpler way to get from p to squash p in a tactic, so that we can use apply_lemma *) let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x /// Calling into the framing tactic to ensure that the vprop whose selector we are trying to access is in the context [@@plugin] let selector_tactic () : Tac unit = apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p) /// Specific tactic used during the SteelAtomicBase and SteelBase effect definitions: /// This allows us to write more complex if_then_else combinators, while proving them /// sound with respect to subcomp [@@ resolve_implicits; ite_attr] let ite_soundness_tac () : Tac unit = let slgs, loggoals = filter_goals (goals ()) in set_goals slgs; solve_indirection_eqs (List.Tot.length slgs); // This is the actual subcomp goal. We can only solve it // once all uvars are solved let subcomp_goal = _cur_goal () in match goals () with | [] -> fail "should not happen" | _::tl -> set_goals tl; or_else (fun _ -> apply_lemma (`equiv_forall_refl)) assumption; or_else (fun _ -> or_else (fun _ -> apply_lemma (`can_be_split_dep_refl)) (fun _ -> apply_lemma (`can_be_split_refl)) // Different formalism in Steel.ST ) assumption; // Discharging the maybe_emp by SMT smt (); // Now propagating all equalities for the requires/ensures set_goals loggoals; resolve_tac_logical []; // Now taking care of the actual subcomp VC set_goals [subcomp_goal]; norm []; smt () /// Normalization step for VC generation, used in Steel and SteelAtomic subcomps /// This tactic is executed after frame inference, and just before sending the query to the SMT /// As such, it is a good place to add debugging features to inspect SMT queries when needed let vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> norm normal_steps; trefl()) //////////////////////////////////////////////////////////////////////////////// //Common datatypes for the atomic & ghost effects //////////////////////////////////////////////////////////////////////////////// /// A datatype indicating whether a computation is ghost (unobservable) or not type observability : eqtype = | Observable | Unobservable (* Helpers to handle observability inside atomic computations *)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
o1: Steel.Effect.Common.observability -> o2: Steel.Effect.Common.observability -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.observability", "Prims.op_BarBar", "Prims.op_Equality", "Steel.Effect.Common.Unobservable", "Prims.bool" ]
[]
false
false
false
true
false
let obs_at_most_one (o1 o2: observability) =
o1 = Unobservable || o2 = Unobservable
false
Steel.Effect.Common.fsti
Steel.Effect.Common.is_true
val is_true: t: term -> Prims.unit -> Tac unit
val is_true: t: term -> Prims.unit -> Tac unit
let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 31, "end_line": 3025, "start_col": 0, "start_line": 3022 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Tactics.NamedView.term -> _: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.unit", "FStar.Tactics.V2.Derived.exact", "FStar.Reflection.V2.Formula.formula", "FStar.Tactics.Effect.raise", "FStar.Tactics.V2.Derived.Goal_not_trivial", "FStar.Reflection.V2.Formula.term_as_formula" ]
[]
false
true
false
false
false
let is_true (t: term) () : Tac unit =
match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial
false
Steel.Effect.Common.fsti
Steel.Effect.Common.print_goals
val print_goals (g: list goal) : Tac string
val print_goals (g: list goal) : Tac string
let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 25, "end_line": 3070, "start_col": 0, "start_line": 3068 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
g: Prims.list FStar.Stubs.Tactics.Types.goal -> FStar.Tactics.Effect.Tac Prims.string
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Tactics.Types.goal", "FStar.String.concat", "Prims.string", "FStar.Tactics.Util.map", "Steel.Effect.Common.print_goal" ]
[]
false
true
false
false
false
let print_goals (g: list goal) : Tac string =
let strs = map print_goal g in String.concat "\n" strs
false
Steel.Effect.Common.fsti
Steel.Effect.Common.inv
val inv (p: vprop) : Type0
val inv (p: vprop) : Type0
let inv (p:vprop) : Type0 = Mem.inv (hp_of p)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 45, "end_line": 3201, "start_col": 0, "start_line": 3201 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' [] (* AF: There probably is a simpler way to get from p to squash p in a tactic, so that we can use apply_lemma *) let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x /// Calling into the framing tactic to ensure that the vprop whose selector we are trying to access is in the context [@@plugin] let selector_tactic () : Tac unit = apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p) /// Specific tactic used during the SteelAtomicBase and SteelBase effect definitions: /// This allows us to write more complex if_then_else combinators, while proving them /// sound with respect to subcomp [@@ resolve_implicits; ite_attr] let ite_soundness_tac () : Tac unit = let slgs, loggoals = filter_goals (goals ()) in set_goals slgs; solve_indirection_eqs (List.Tot.length slgs); // This is the actual subcomp goal. We can only solve it // once all uvars are solved let subcomp_goal = _cur_goal () in match goals () with | [] -> fail "should not happen" | _::tl -> set_goals tl; or_else (fun _ -> apply_lemma (`equiv_forall_refl)) assumption; or_else (fun _ -> or_else (fun _ -> apply_lemma (`can_be_split_dep_refl)) (fun _ -> apply_lemma (`can_be_split_refl)) // Different formalism in Steel.ST ) assumption; // Discharging the maybe_emp by SMT smt (); // Now propagating all equalities for the requires/ensures set_goals loggoals; resolve_tac_logical []; // Now taking care of the actual subcomp VC set_goals [subcomp_goal]; norm []; smt () /// Normalization step for VC generation, used in Steel and SteelAtomic subcomps /// This tactic is executed after frame inference, and just before sending the query to the SMT /// As such, it is a good place to add debugging features to inspect SMT queries when needed let vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> norm normal_steps; trefl()) //////////////////////////////////////////////////////////////////////////////// //Common datatypes for the atomic & ghost effects //////////////////////////////////////////////////////////////////////////////// /// A datatype indicating whether a computation is ghost (unobservable) or not type observability : eqtype = | Observable | Unobservable (* Helpers to handle observability inside atomic computations *) unfold let obs_at_most_one (o1 o2:observability) = o1=Unobservable || o2=Unobservable unfold let join_obs (o1:observability) (o2:observability) = if o1 = Observable || o2 = Observable then Observable else Unobservable (* Lifting invariants to vprops *) /// [i : inv p] is an invariant whose content is [p]
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: Steel.Effect.Common.vprop -> Type0
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.vprop", "Steel.Memory.inv", "Steel.Effect.Common.hp_of" ]
[]
false
false
false
true
true
let inv (p: vprop) : Type0 =
Mem.inv (hp_of p)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.dismiss_all_but_last'
val dismiss_all_but_last' (l: list goal) : Tac unit
val dismiss_all_but_last' (l: list goal) : Tac unit
let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 37, "end_line": 2174, "start_col": 0, "start_line": 2171 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Prims.list FStar.Stubs.Tactics.Types.goal -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Tactics.Types.goal", "FStar.Stubs.Tactics.V2.Builtins.set_goals", "Prims.unit", "Steel.Effect.Common.dismiss_all_but_last'" ]
[ "recursion" ]
false
true
false
false
false
let rec dismiss_all_but_last' (l: list goal) : Tac unit =
match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q
false
Steel.Effect.Common.fsti
Steel.Effect.Common.dismiss_non_squash_goals'
val dismiss_non_squash_goals' (keep goals: list goal) : Tac unit
val dismiss_non_squash_goals' (keep goals: list goal) : Tac unit
let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 40, "end_line": 2192, "start_col": 0, "start_line": 2179 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ())
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
keep: Prims.list FStar.Stubs.Tactics.Types.goal -> goals: Prims.list FStar.Stubs.Tactics.Types.goal -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Tactics.Types.goal", "FStar.Stubs.Tactics.V2.Builtins.set_goals", "FStar.List.Tot.Base.rev", "Prims.unit", "FStar.Tactics.NamedView.term", "Steel.Effect.Common.is_squash", "Steel.Effect.Common.dismiss_non_squash_goals'", "Prims.Cons", "Prims.bool", "FStar.Reflection.V2.Formula.formula", "FStar.Reflection.V2.Formula.term_as_formula'", "FStar.Stubs.Tactics.Types.goal_type" ]
[ "recursion" ]
false
true
false
false
false
let rec dismiss_non_squash_goals' (keep goals: list goal) : Tac unit =
match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd :: keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl
false
Steel.Effect.Common.fsti
Steel.Effect.Common.join_obs
val join_obs : o1: Steel.Effect.Common.observability -> o2: Steel.Effect.Common.observability -> Steel.Effect.Common.observability
let join_obs (o1:observability) (o2:observability) = if o1 = Observable || o2 = Observable then Observable else Unobservable
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 19, "end_line": 3195, "start_col": 0, "start_line": 3192 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' [] (* AF: There probably is a simpler way to get from p to squash p in a tactic, so that we can use apply_lemma *) let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x /// Calling into the framing tactic to ensure that the vprop whose selector we are trying to access is in the context [@@plugin] let selector_tactic () : Tac unit = apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p) /// Specific tactic used during the SteelAtomicBase and SteelBase effect definitions: /// This allows us to write more complex if_then_else combinators, while proving them /// sound with respect to subcomp [@@ resolve_implicits; ite_attr] let ite_soundness_tac () : Tac unit = let slgs, loggoals = filter_goals (goals ()) in set_goals slgs; solve_indirection_eqs (List.Tot.length slgs); // This is the actual subcomp goal. We can only solve it // once all uvars are solved let subcomp_goal = _cur_goal () in match goals () with | [] -> fail "should not happen" | _::tl -> set_goals tl; or_else (fun _ -> apply_lemma (`equiv_forall_refl)) assumption; or_else (fun _ -> or_else (fun _ -> apply_lemma (`can_be_split_dep_refl)) (fun _ -> apply_lemma (`can_be_split_refl)) // Different formalism in Steel.ST ) assumption; // Discharging the maybe_emp by SMT smt (); // Now propagating all equalities for the requires/ensures set_goals loggoals; resolve_tac_logical []; // Now taking care of the actual subcomp VC set_goals [subcomp_goal]; norm []; smt () /// Normalization step for VC generation, used in Steel and SteelAtomic subcomps /// This tactic is executed after frame inference, and just before sending the query to the SMT /// As such, it is a good place to add debugging features to inspect SMT queries when needed let vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> norm normal_steps; trefl()) //////////////////////////////////////////////////////////////////////////////// //Common datatypes for the atomic & ghost effects //////////////////////////////////////////////////////////////////////////////// /// A datatype indicating whether a computation is ghost (unobservable) or not type observability : eqtype = | Observable | Unobservable (* Helpers to handle observability inside atomic computations *) unfold let obs_at_most_one (o1 o2:observability) = o1=Unobservable || o2=Unobservable
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
o1: Steel.Effect.Common.observability -> o2: Steel.Effect.Common.observability -> Steel.Effect.Common.observability
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.observability", "Prims.op_BarBar", "Prims.op_Equality", "Steel.Effect.Common.Observable", "Prims.bool", "Steel.Effect.Common.Unobservable" ]
[]
false
false
false
true
false
let join_obs (o1 o2: observability) =
if o1 = Observable || o2 = Observable then Observable else Unobservable
false
Steel.Effect.Common.fsti
Steel.Effect.Common.add_inv
val add_inv (#p: vprop) (e: inames) (i: inv p) : inames
val add_inv (#p: vprop) (e: inames) (i: inv p) : inames
let add_inv (#p:vprop) (e:inames) (i:inv p) : inames = Set.union (Set.singleton (name_of_inv i)) (reveal e)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 54, "end_line": 3211, "start_col": 0, "start_line": 3210 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' [] (* AF: There probably is a simpler way to get from p to squash p in a tactic, so that we can use apply_lemma *) let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x /// Calling into the framing tactic to ensure that the vprop whose selector we are trying to access is in the context [@@plugin] let selector_tactic () : Tac unit = apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p) /// Specific tactic used during the SteelAtomicBase and SteelBase effect definitions: /// This allows us to write more complex if_then_else combinators, while proving them /// sound with respect to subcomp [@@ resolve_implicits; ite_attr] let ite_soundness_tac () : Tac unit = let slgs, loggoals = filter_goals (goals ()) in set_goals slgs; solve_indirection_eqs (List.Tot.length slgs); // This is the actual subcomp goal. We can only solve it // once all uvars are solved let subcomp_goal = _cur_goal () in match goals () with | [] -> fail "should not happen" | _::tl -> set_goals tl; or_else (fun _ -> apply_lemma (`equiv_forall_refl)) assumption; or_else (fun _ -> or_else (fun _ -> apply_lemma (`can_be_split_dep_refl)) (fun _ -> apply_lemma (`can_be_split_refl)) // Different formalism in Steel.ST ) assumption; // Discharging the maybe_emp by SMT smt (); // Now propagating all equalities for the requires/ensures set_goals loggoals; resolve_tac_logical []; // Now taking care of the actual subcomp VC set_goals [subcomp_goal]; norm []; smt () /// Normalization step for VC generation, used in Steel and SteelAtomic subcomps /// This tactic is executed after frame inference, and just before sending the query to the SMT /// As such, it is a good place to add debugging features to inspect SMT queries when needed let vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> norm normal_steps; trefl()) //////////////////////////////////////////////////////////////////////////////// //Common datatypes for the atomic & ghost effects //////////////////////////////////////////////////////////////////////////////// /// A datatype indicating whether a computation is ghost (unobservable) or not type observability : eqtype = | Observable | Unobservable (* Helpers to handle observability inside atomic computations *) unfold let obs_at_most_one (o1 o2:observability) = o1=Unobservable || o2=Unobservable unfold let join_obs (o1:observability) (o2:observability) = if o1 = Observable || o2 = Observable then Observable else Unobservable (* Lifting invariants to vprops *) /// [i : inv p] is an invariant whose content is [p] inline_for_extraction let inv (p:vprop) : Type0 = Mem.inv (hp_of p) let name_of_inv (#p:vprop) (i:inv p) : GTot iname = Mem.name_of_inv i /// Ghost check to determing whether invariant [i] belongs to the set of opened invariants [e] let mem_inv (#p:vprop) (e:inames) (i:inv p) : erased bool = elift2 (fun e i -> Set.mem i e) e (name_of_inv i) /// Adding invariant [i] to the set of opened invariants [e]
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
e: Steel.Memory.inames -> i: Steel.Effect.Common.inv p -> Steel.Memory.inames
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.vprop", "Steel.Memory.inames", "Steel.Effect.Common.inv", "FStar.Ghost.hide", "FStar.Set.set", "Steel.Memory.iname", "FStar.Set.union", "FStar.Set.singleton", "Steel.Effect.Common.name_of_inv", "FStar.Ghost.reveal" ]
[]
false
false
false
false
false
let add_inv (#p: vprop) (e: inames) (i: inv p) : inames =
Set.union (Set.singleton (name_of_inv i)) (reveal e)
false
Example.fst
Example.l_reverse
val l_reverse (l: list 'a) : GTot (list 'a)
val l_reverse (l: list 'a) : GTot (list 'a)
let rec l_reverse (l:list 'a) : GTot (list 'a) = match l with | [] -> [] | hd :: tl -> L.snoc ((l_reverse tl), hd)
{ "file_name": "examples/doublylinkedlist/Example.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 31, "end_line": 31, "start_col": 0, "start_line": 27 }
(* Copyright 2008-2019 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Example module HS = FStar.HyperStack module HST = FStar.HyperStack.ST module B = LowStar.Buffer module DLL = DoublyLinkedListIface module L = FStar.List.Tot open DoublyLinkedListIface
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowStar.Buffer.fst.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked", "DoublyLinkedListIface.fsti.checked" ], "interface_file": false, "source_file": "Example.fst" }
[ { "abbrev": false, "full_module": "DoublyLinkedListIface", "short_module": null }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "DoublyLinkedListIface", "short_module": "DLL" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": true, "full_module": "FStar.HyperStack.ST", "short_module": "HST" }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Prims.list 'a -> Prims.GTot (Prims.list 'a)
Prims.GTot
[ "sometrivial" ]
[]
[ "Prims.list", "Prims.Nil", "FStar.List.Tot.Base.snoc", "FStar.Pervasives.Native.Mktuple2", "Example.l_reverse" ]
[ "recursion" ]
false
false
false
false
false
let rec l_reverse (l: list 'a) : GTot (list 'a) =
match l with | [] -> [] | hd :: tl -> L.snoc ((l_reverse tl), hd)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.bring_last_goal_on_top'
val bring_last_goal_on_top' (others goals: list goal) : Tac unit
val bring_last_goal_on_top' (others goals: list goal) : Tac unit
let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 53, "end_line": 2230, "start_col": 0, "start_line": 2226 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
others: Prims.list FStar.Stubs.Tactics.Types.goal -> goals: Prims.list FStar.Stubs.Tactics.Types.goal -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Stubs.Tactics.Types.goal", "FStar.Stubs.Tactics.V2.Builtins.set_goals", "FStar.List.Tot.Base.rev", "Prims.unit", "Prims.Cons", "Steel.Effect.Common.bring_last_goal_on_top'" ]
[ "recursion" ]
false
true
false
false
false
let rec bring_last_goal_on_top' (others goals: list goal) : Tac unit =
match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q
false
Steel.Effect.Common.fsti
Steel.Effect.Common.mem_inv
val mem_inv (#p: vprop) (e: inames) (i: inv p) : erased bool
val mem_inv (#p: vprop) (e: inames) (i: inv p) : erased bool
let mem_inv (#p:vprop) (e:inames) (i:inv p) : erased bool = elift2 (fun e i -> Set.mem i e) e (name_of_inv i)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 109, "end_line": 3206, "start_col": 0, "start_line": 3206 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' [] (* AF: There probably is a simpler way to get from p to squash p in a tactic, so that we can use apply_lemma *) let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x /// Calling into the framing tactic to ensure that the vprop whose selector we are trying to access is in the context [@@plugin] let selector_tactic () : Tac unit = apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p) /// Specific tactic used during the SteelAtomicBase and SteelBase effect definitions: /// This allows us to write more complex if_then_else combinators, while proving them /// sound with respect to subcomp [@@ resolve_implicits; ite_attr] let ite_soundness_tac () : Tac unit = let slgs, loggoals = filter_goals (goals ()) in set_goals slgs; solve_indirection_eqs (List.Tot.length slgs); // This is the actual subcomp goal. We can only solve it // once all uvars are solved let subcomp_goal = _cur_goal () in match goals () with | [] -> fail "should not happen" | _::tl -> set_goals tl; or_else (fun _ -> apply_lemma (`equiv_forall_refl)) assumption; or_else (fun _ -> or_else (fun _ -> apply_lemma (`can_be_split_dep_refl)) (fun _ -> apply_lemma (`can_be_split_refl)) // Different formalism in Steel.ST ) assumption; // Discharging the maybe_emp by SMT smt (); // Now propagating all equalities for the requires/ensures set_goals loggoals; resolve_tac_logical []; // Now taking care of the actual subcomp VC set_goals [subcomp_goal]; norm []; smt () /// Normalization step for VC generation, used in Steel and SteelAtomic subcomps /// This tactic is executed after frame inference, and just before sending the query to the SMT /// As such, it is a good place to add debugging features to inspect SMT queries when needed let vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> norm normal_steps; trefl()) //////////////////////////////////////////////////////////////////////////////// //Common datatypes for the atomic & ghost effects //////////////////////////////////////////////////////////////////////////////// /// A datatype indicating whether a computation is ghost (unobservable) or not type observability : eqtype = | Observable | Unobservable (* Helpers to handle observability inside atomic computations *) unfold let obs_at_most_one (o1 o2:observability) = o1=Unobservable || o2=Unobservable unfold let join_obs (o1:observability) (o2:observability) = if o1 = Observable || o2 = Observable then Observable else Unobservable (* Lifting invariants to vprops *) /// [i : inv p] is an invariant whose content is [p] inline_for_extraction let inv (p:vprop) : Type0 = Mem.inv (hp_of p) let name_of_inv (#p:vprop) (i:inv p) : GTot iname = Mem.name_of_inv i
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
e: Steel.Memory.inames -> i: Steel.Effect.Common.inv p -> FStar.Ghost.erased Prims.bool
Prims.Tot
[ "total" ]
[]
[ "Steel.Effect.Common.vprop", "Steel.Memory.inames", "Steel.Effect.Common.inv", "FStar.Ghost.elift2", "FStar.Set.set", "Steel.Memory.iname", "Prims.bool", "FStar.Set.mem", "FStar.Ghost.hide", "Steel.Effect.Common.name_of_inv", "FStar.Ghost.erased" ]
[]
false
false
false
false
false
let mem_inv (#p: vprop) (e: inames) (i: inv p) : erased bool =
elift2 (fun e i -> Set.mem i e) e (name_of_inv i)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.open_existentials
val open_existentials: Prims.unit -> Tac unit
val open_existentials: Prims.unit -> Tac unit
let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal"
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 57, "end_line": 2326, "start_col": 0, "start_line": 2300 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "FStar.Tactics.NamedView.term", "FStar.Stubs.Reflection.Types.term", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Reflection.V2.Derived.is_fvar", "FStar.Tactics.V2.Derived.fail", "Steel.Effect.Common.bring_last_goal_on_top", "FStar.Tactics.V2.Derived.focus", "FStar.Tactics.V2.Logic.split", "Steel.Effect.Common.dismiss_all_but_last", "FStar.Tactics.V2.Derived.apply_lemma", "FStar.Pervasives.Native.option", "Steel.Effect.Common.extract_cbs_contexts", "Prims.bool", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app", "FStar.Stubs.Reflection.Types.typ", "FStar.Tactics.V2.Derived.cur_goal", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_attr", "Prims.string", "Prims.Nil", "Prims.uu___is_Nil", "FStar.Stubs.Reflection.Types.fv", "FStar.Stubs.Reflection.V2.Builtins.lookup_attr", "FStar.Stubs.Reflection.Types.env", "FStar.Tactics.V2.Derived.cur_env" ]
[]
false
true
false
false
false
let open_existentials () : Tac unit =
let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _, (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ :: (rhs, Q_Explicit) :: [] -> (match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top ()) | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal"
false
Steel.Effect.Common.fsti
Steel.Effect.Common.selector_tactic
val selector_tactic: Prims.unit -> Tac unit
val selector_tactic: Prims.unit -> Tac unit
let selector_tactic () : Tac unit = apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 34, "end_line": 3137, "start_col": 0, "start_line": 3125 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g let compute_guarded_uvars () : Tac (list int) = let g = goals () in let accu = compute_guarded_uvars1 [] g in compute_guarded_uvars3 accu g let rec pick_next (guarded_uvars: list int) (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | a::_ -> let t = goal_type a in let l = goal_term_uvars t in let next () : Tac bool = later (); pick_next guarded_uvars dict (fuel - 1) in if sorted_lists_intersect guarded_uvars l then next () else if solve_or_delay dict then true else next () /// Main loop to schedule solving of goals. /// The goals () function fetches all current goals in the context let rec resolve_tac (dict: _) : Tac unit = match goals () with | [] -> () | g -> norm []; let guarded_uvars = compute_guarded_uvars () in // TODO: If it picks a goal it cannot solve yet, try all the other ones? if pick_next guarded_uvars dict (List.Tot.length g) then resolve_tac dict else fail "Could not make progress, no solvable goal found" let rec pick_next_logical (dict: _) (fuel: nat) : Tac bool = if fuel = 0 then false else match goals () with | [] -> true | _::_ -> if solve_or_delay dict then true else (later (); pick_next_logical dict (fuel - 1)) /// Special case for logical requires/ensures goals, which correspond only to equalities let rec resolve_tac_logical (dict: _) : Tac unit = match goals () with | [] -> () | g -> let fuel = List.Tot.length g in if pick_next_logical dict fuel then resolve_tac_logical dict else // This is only for requires/ensures constraints, which are equalities // There should always be a scheduling of constraints, but it can happen // that some uvar for the type of an equality is not resolved. // If we reach this point, we try to simply call the unifier instead of failing directly solve_all_eqs fuel /// Determining whether the type represented by term [t] corresponds to one of the logical (requires/ensures) goals let typ_contains_req_ens (t:term) : Tac bool = let name, _ = collect_app t in is_any_fvar name [`%req_t; `%ens_t; `%pure_wp; `%pure_pre; `%pure_post] /// Splits goals between separation logic goals (slgoals) and requires/ensures goals (loggoals) let rec filter_goals (l:list goal) : Tac (list goal * list goal) = match l with | [] -> [], [] | hd::tl -> let slgoals, loggoals = filter_goals tl in match term_as_formula' (goal_type hd) with | Comp (Eq t) _ _ -> if Some? t then let b = typ_contains_req_ens (Some?.v t) in if b then ( slgoals, hd::loggoals ) else ( hd::slgoals, loggoals ) else ( hd::slgoals, loggoals ) | App t _ -> if is_fvar t (`%squash) then hd::slgoals, loggoals else slgoals, loggoals | _ -> slgoals, loggoals let is_true (t:term) () : Tac unit = match term_as_formula t with | True_ -> exact (`()) | _ -> raise Goal_not_trivial /// Solve the maybe_emp goals: /// Normalize to unfold maybe_emp(_dep) and the reduce the if/then/else, and /// solve the goal (either an equality through trefl, or True through trivial) let rec solve_maybe_emps (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> let f = term_as_formula' (cur_goal ()) in ( match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then later () else let hd, args = collect_app t in if hd `is_fvar` (`%maybe_emp) then (norm [delta_only [`%maybe_emp]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) trefl) else if hd `is_fvar` (`%maybe_emp_dep) then (norm [delta_only [`%maybe_emp_dep]; iota; zeta; primops; simplify]; let g = cur_goal () in or_else (is_true g) (fun _ -> ignore (forall_intro ()); trefl ())) else later() | _ -> later() ); solve_maybe_emps (fuel - 1) /// Normalizes all the return_pre annotations once they are not needed anymore let rec norm_return_pre (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | _::_ -> norm [delta_only [`%return_pre]]; later(); norm_return_pre (fuel - 1) let print_goal (g:goal) : Tac string = let t = goal_type g in term_to_string t let print_goals (g:list goal) : Tac string = let strs = map print_goal g in String.concat "\n" strs /// The entry point of the frame inference tactic: /// The resolve_implicits; framing_implicit annotation indicates that this tactic should /// be called by the F* typechecker to solve all implicits annotated with the `framing_implicit` attribute. /// The `plugin` attribute ensures that this tactic is compiled, and executed natively for performance reasons let init_resolve_tac' (dict: _) : Tac unit = // We split goals between framing goals, about slprops (slgs) // and goals related to requires/ensures, that depend on slprops (loggs) let slgs, loggs = filter_goals (goals()) in // print ("SL Goals: \n" ^ print_goals slgs); // print ("Logical goals: \n" ^ print_goals loggs); // We first solve the slprops set_goals slgs; // We solve all the maybe_emp goals first: All "extra" frames are directly set to emp solve_maybe_emps (List.Tot.length (goals ())); // We first solve all indirection equalities that will not lead to imprecise unification // i.e. we can solve all equalities inserted by layered effects, except the ones corresponding // to the preconditions of a pure return solve_indirection_eqs (List.Tot.length (goals())); // To debug, it is best to look at the goals at this stage. Uncomment the next line // dump "initial goals"; // We can now solve the equalities for returns solve_return_eqs (List.Tot.length (goals())); // It is important to not normalize the return_pre equalities before solving them // Else, we lose some variables dependencies, leading to the tactic being stuck // See test7 in FramingTestSuite for more explanations of what is failing // Once unification has been done, we can then safely normalize and remove all return_pre norm_return_pre (List.Tot.length (goals())); // Finally running the core of the tactic, scheduling and solving goals resolve_tac dict; // We now solve the requires/ensures goals, which are all equalities // All slprops are resolved by now set_goals loggs; resolve_tac_logical dict [@@ resolve_implicits; framing_implicit; plugin] let init_resolve_tac () : Tac unit = init_resolve_tac' [] (* AF: There probably is a simpler way to get from p to squash p in a tactic, so that we can use apply_lemma *) let squash_and p (x:squash (p /\ True)) : (p /\ True) = let x : squash (p `Prims.pair` True) = FStar.Squash.join_squash x in x /// Calling into the framing tactic to ensure that the vprop whose selector we are trying to access is in the context
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Steel.Effect.Common.canon'", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta_only", "Prims.string", "Prims.Nil", "FStar.Pervasives.delta_attr", "FStar.Pervasives.primops", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Tactics.V2.Derived.flip", "FStar.Tactics.V2.Derived.apply_lemma", "FStar.Tactics.V2.Derived.apply" ]
[]
false
true
false
false
false
let selector_tactic () : Tac unit =
apply (`squash_and); apply_lemma (`intro_can_be_split_frame); flip (); norm [ delta_only [ `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd ]; delta_attr [`%__reduce__]; primops; iota; zeta ]; canon' false (`true_p) (`true_p)
false
Example.fst
Example.reverse
val reverse (d: dll 'a) : HST.Stack (unit) (fun h0 -> dll_valid h0 d) (fun h0 () h1 -> dll_valid h1 d /\ as_list h1 d == l_reverse (as_list h0 d) /\ as_payload_list h1 d == l_reverse (as_payload_list h0 d) /\ B.modifies (fp_dll h0 d) h0 h1 /\ (fp_dll h0 d) `loc_equiv` (fp_dll h1 d))
val reverse (d: dll 'a) : HST.Stack (unit) (fun h0 -> dll_valid h0 d) (fun h0 () h1 -> dll_valid h1 d /\ as_list h1 d == l_reverse (as_list h0 d) /\ as_payload_list h1 d == l_reverse (as_payload_list h0 d) /\ B.modifies (fp_dll h0 d) h0 h1 /\ (fp_dll h0 d) `loc_equiv` (fp_dll h1 d))
let rec reverse (d:dll 'a) : HST.Stack (unit) (fun h0 -> dll_valid h0 d) (fun h0 () h1 -> dll_valid h1 d /\ as_list h1 d == l_reverse (as_list h0 d) /\ as_payload_list h1 d == l_reverse (as_payload_list h0 d) /\ B.modifies (fp_dll h0 d) h0 h1 /\ fp_dll h0 d `loc_equiv` fp_dll h1 d) = HST.push_frame (); if is_empty d then ( () ) else ( let n = dll_head d in dll_remove_head d; reverse d; dll_insert_at_tail d n ); HST.pop_frame ()
{ "file_name": "examples/doublylinkedlist/Example.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 18, "end_line": 51, "start_col": 0, "start_line": 33 }
(* Copyright 2008-2019 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Example module HS = FStar.HyperStack module HST = FStar.HyperStack.ST module B = LowStar.Buffer module DLL = DoublyLinkedListIface module L = FStar.List.Tot open DoublyLinkedListIface let rec l_reverse (l:list 'a) : GTot (list 'a) = match l with | [] -> [] | hd :: tl -> L.snoc ((l_reverse tl), hd)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowStar.Buffer.fst.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked", "DoublyLinkedListIface.fsti.checked" ], "interface_file": false, "source_file": "Example.fst" }
[ { "abbrev": false, "full_module": "DoublyLinkedListIface", "short_module": null }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "DoublyLinkedListIface", "short_module": "DLL" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": true, "full_module": "FStar.HyperStack.ST", "short_module": "HST" }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
d: DoublyLinkedListIface.dll 'a -> FStar.HyperStack.ST.Stack Prims.unit
FStar.HyperStack.ST.Stack
[]
[]
[ "DoublyLinkedListIface.dll", "FStar.HyperStack.ST.pop_frame", "Prims.unit", "Prims.bool", "DoublyLinkedListIface.dll_insert_at_tail", "Example.reverse", "DoublyLinkedListIface.dll_remove_head", "DoublyLinkedListIface.node", "DoublyLinkedListIface.dll_head", "DoublyLinkedListIface.is_empty", "FStar.HyperStack.ST.push_frame", "FStar.Monotonic.HyperStack.mem", "DoublyLinkedListIface.dll_valid", "Prims.l_and", "Prims.eq2", "Prims.list", "DoublyLinkedListIface.as_list", "Example.l_reverse", "DoublyLinkedListIface.as_payload_list", "LowStar.Monotonic.Buffer.modifies", "DoublyLinkedListIface.fp_dll", "DoublyLinkedListIface.loc_equiv" ]
[ "recursion" ]
false
true
false
false
false
let rec reverse (d: dll 'a) : HST.Stack (unit) (fun h0 -> dll_valid h0 d) (fun h0 () h1 -> dll_valid h1 d /\ as_list h1 d == l_reverse (as_list h0 d) /\ as_payload_list h1 d == l_reverse (as_payload_list h0 d) /\ B.modifies (fp_dll h0 d) h0 h1 /\ (fp_dll h0 d) `loc_equiv` (fp_dll h1 d)) =
HST.push_frame (); if is_empty d then (()) else (let n = dll_head d in dll_remove_head d; reverse d; dll_insert_at_tail d n); HST.pop_frame ()
false
Steel.Effect.Common.fsti
Steel.Effect.Common.remove_dups_from_sorted
val remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t)
val remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t)
let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 115, "end_line": 2858, "start_col": 0, "start_line": 2856 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t ()
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Prims.list t -> Prims.list t
Prims.Tot
[ "total" ]
[]
[ "Prims.eqtype", "Prims.list", "Prims.op_Equality", "Steel.Effect.Common.remove_dups_from_sorted", "Prims.Cons", "Prims.bool" ]
[ "recursion" ]
false
false
false
false
false
let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) =
match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.term_dict_assoc
val term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a)
val term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a)
let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q'
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 11, "end_line": 2782, "start_col": 0, "start_line": 2771 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal")
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
key: FStar.Tactics.NamedView.term -> l: Prims.list (FStar.Tactics.NamedView.term * a) -> FStar.Tactics.Effect.Tac (Prims.list a)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Pervasives.Native.tuple2", "Prims.Nil", "Prims.Cons", "Prims.bool", "FStar.Stubs.Tactics.V2.Builtins.term_eq_old", "Steel.Effect.Common.term_dict_assoc" ]
[ "recursion" ]
false
true
false
false
false
let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) =
match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q'
false
Steel.Effect.Common.fsti
Steel.Effect.Common.extract_contexts
val extract_contexts (lemma_left lemma_right label_attr attr t: term) : Tac (option (unit -> Tac unit))
val extract_contexts (lemma_left lemma_right label_attr attr t: term) : Tac (option (unit -> Tac unit))
let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () )
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 7, "end_line": 2292, "start_col": 0, "start_line": 2236 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
lemma_left: FStar.Tactics.NamedView.term -> lemma_right: FStar.Tactics.NamedView.term -> label_attr: FStar.Tactics.NamedView.term -> attr: FStar.Tactics.NamedView.term -> t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Pervasives.Native.option (_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit))
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "Steel.Effect.Common.is_star", "FStar.Stubs.Reflection.Types.term", "FStar.Pervasives.Native.option", "Prims.unit", "FStar.Pervasives.Native.Some", "FStar.Tactics.V2.Derived.try_with", "Steel.Effect.Common.dismiss_all_but_last", "FStar.Tactics.V2.Derived.apply_lemma", "Prims.exn", "FStar.Tactics.V2.Derived.fail", "Steel.Effect.Common.extract_contexts", "FStar.Pervasives.Native.None", "Prims.bool", "Prims.uu___is_Nil", "FStar.Stubs.Reflection.Types.fv", "Steel.Effect.Common.dismiss_non_squash_goals", "FStar.Tactics.V2.Derived.first", "FStar.List.Tot.Base.map", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_FVar", "Prims.Nil", "Steel.Effect.Common.lookup_by_term_attr", "FStar.Reflection.V2.Derived.mk_app", "Prims.Cons", "FStar.Pervasives.Native.Mktuple2", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "FStar.Tactics.NamedView.Tv_Const", "FStar.Stubs.Reflection.V2.Data.C_String", "Prims.string", "FStar.Stubs.Reflection.V2.Builtins.implode_qn", "FStar.Stubs.Reflection.V2.Builtins.inspect_fv", "FStar.Stubs.Reflection.V2.Data.universes", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.NamedView.term_view", "Prims.b2t", "FStar.Tactics.NamedView.notAscription", "FStar.Tactics.V2.SyntaxHelpers.inspect_unascribe", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V2.SyntaxHelpers.collect_app" ]
[ "recursion" ]
false
true
false
false
false
let rec extract_contexts (lemma_left lemma_right label_attr attr t: term) : Tac (option (unit -> Tac unit)) =
let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f ()) in (match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try (apply_lemma lemma_left; dismiss_all_but_last (); f ()) with | _ -> match extract_right () with | None -> fail "no context on the right either" | Some g -> g ())) | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals ())
false
Steel.Effect.Common.fsti
Steel.Effect.Common.merge_sorted
val merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2))
val merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2))
let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 5, "end_line": 2888, "start_col": 0, "start_line": 2875 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else []
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l1: Prims.list Prims.int -> l2: Prims.list Prims.int -> Prims.Tot (Prims.list Prims.int)
Prims.Tot
[ "total", "" ]
[]
[ "Prims.list", "Prims.int", "Prims.op_LessThan", "Prims.Cons", "Steel.Effect.Common.merge_sorted", "Prims.bool" ]
[ "recursion" ]
false
false
false
true
false
let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) =
match l1 with | [] -> l2 | a1 :: q1 -> match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_all_eqs
val solve_all_eqs (fuel: nat) : Tac unit
val solve_all_eqs (fuel: nat) : Tac unit
let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 44, "end_line": 2723, "start_col": 0, "start_line": 2712 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1)
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
fuel: Prims.nat -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.nat", "Prims.op_Equality", "Prims.int", "Prims.unit", "Prims.bool", "FStar.Stubs.Tactics.Types.goal", "Prims.list", "FStar.Pervasives.Native.option", "FStar.Stubs.Reflection.Types.typ", "FStar.Tactics.NamedView.term", "Steel.Effect.Common.solve_all_eqs", "Prims.op_Subtraction", "FStar.Tactics.V2.Derived.trefl", "FStar.Reflection.V2.Formula.formula", "FStar.Tactics.V2.Derived.later", "FStar.Reflection.V2.Formula.term_as_formula'", "FStar.Stubs.Tactics.Types.goal_type", "FStar.Tactics.V2.Derived.goals" ]
[ "recursion" ]
false
true
false
false
false
let rec solve_all_eqs (fuel: nat) : Tac unit =
if fuel = 0 then () else match goals () with | [] -> () | hd :: _ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl (); solve_all_eqs (fuel - 1) | _ -> later (); solve_all_eqs (fuel - 1)
false
Steel.Effect.Common.fsti
Steel.Effect.Common.canon_monoid
val canon_monoid (use_smt: bool) (carrier_t eq m pr pr_bind: term) : Tac unit
val canon_monoid (use_smt: bool) (carrier_t eq m pr pr_bind: term) : Tac unit
let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation")
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 68, "end_line": 2103, "start_col": 0, "start_line": 2082 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
use_smt: Prims.bool -> carrier_t: FStar.Tactics.NamedView.term -> eq: FStar.Tactics.NamedView.term -> m: FStar.Tactics.NamedView.term -> pr: FStar.Tactics.NamedView.term -> pr_bind: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.bool", "FStar.Tactics.NamedView.term", "FStar.Stubs.Reflection.Types.term", "Prims.l_or", "Prims.eq2", "Prims.precedes", "Prims.list", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Pervasives.Native.fst", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.op_GreaterThanOrEqual", "FStar.List.Tot.Base.length", "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.tuple2", "FStar.List.Tot.Base.index", "Prims.op_Subtraction", "Steel.Effect.Common.canon_l_r", "Prims.unit", "FStar.Tactics.V2.Derived.fail", "FStar.Reflection.V2.Derived.Lemmas.collect_app_ref", "FStar.Stubs.Reflection.Types.typ", "FStar.Tactics.V2.Derived.cur_goal", "FStar.Stubs.Tactics.V2.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "Prims.Nil" ]
[]
false
true
false
false
false
let canon_monoid (use_smt: bool) (carrier_t eq m pr pr_bind: term) : Tac unit =
norm [iota; zeta]; let t = cur_goal () in let sq, rel_xy = collect_app_ref t in (match rel_xy with | [rel_xy, _] -> (let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then (match index xy (length xy - 2), index xy (length xy - 1) with | (lhs, Q_Explicit), (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else (fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" )) | _ -> fail "Goal should be squash applied to a binary relation")
false
Steel.Effect.Common.fsti
Steel.Effect.Common.compute_guarded_uvars3
val compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int)
val compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int)
let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) = let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 37, "end_line": 2937, "start_col": 0, "start_line": 2933 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q /// Enrich the list of vprop uvars with those that appear in the same goal let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
accu: Prims.list Prims.int -> g: Prims.list FStar.Stubs.Tactics.Types.goal -> FStar.Tactics.Effect.Tac (Prims.list Prims.int)
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "Prims.int", "FStar.Stubs.Tactics.Types.goal", "Prims.op_Equality", "Prims.bool", "Steel.Effect.Common.compute_guarded_uvars3", "Steel.Effect.Common.compute_guarded_uvars2" ]
[ "recursion" ]
false
true
false
false
false
let rec compute_guarded_uvars3 (accu: list int) (g: list goal) : Tac (list int) =
let accu' = compute_guarded_uvars2 accu g in if accu = accu' then accu else compute_guarded_uvars3 accu' g
false
Steel.Effect.Common.fsti
Steel.Effect.Common.compute_guarded_uvars2
val compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int)
val compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int)
let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 34, "end_line": 2931, "start_col": 0, "start_line": 2920 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times /// Compute the list of all vprop uvars that appear in the same goal as unsolved guard_vprop let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
accu: Prims.list Prims.int -> g: Prims.list FStar.Stubs.Tactics.Types.goal -> FStar.Tactics.Effect.Tac (Prims.list Prims.int)
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "Prims.int", "FStar.Stubs.Tactics.Types.goal", "Steel.Effect.Common.compute_guarded_uvars2", "Steel.Effect.Common.sorted_lists_intersect", "Steel.Effect.Common.merge_sorted", "Prims.bool", "Steel.Effect.Common.goal_term_uvars", "FStar.Stubs.Reflection.Types.typ", "FStar.Stubs.Tactics.Types.goal_type" ]
[ "recursion" ]
false
true
false
false
false
let rec compute_guarded_uvars2 (accu: list int) (g: list goal) : Tac (list int) =
match g with | [] -> accu | a :: q -> let t = goal_type a in let l = goal_term_uvars t in let accu' = if sorted_lists_intersect accu l then merge_sorted accu l else accu in compute_guarded_uvars2 accu' q
false
Steel.Effect.Common.fsti
Steel.Effect.Common.compute_guarded_uvars1
val compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int)
val compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int)
let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) = match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 34, "end_line": 2917, "start_col": 0, "start_line": 2907 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end /// TODO: cache the list of variables for each goal, to avoid computing them several times
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
accu: Prims.list Prims.int -> g: Prims.list FStar.Stubs.Tactics.Types.goal -> FStar.Tactics.Effect.Tac (Prims.list Prims.int)
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "Prims.int", "FStar.Stubs.Tactics.Types.goal", "Steel.Effect.Common.compute_guarded_uvars1", "Prims.bool", "Steel.Effect.Common.merge_sorted", "Steel.Effect.Common.goal_term_uvars", "Steel.Effect.Common.all_guards_solved", "FStar.Stubs.Reflection.Types.typ", "FStar.Stubs.Tactics.Types.goal_type" ]
[ "recursion" ]
false
true
false
false
false
let rec compute_guarded_uvars1 (accu: list int) (g: list goal) : Tac (list int) =
match g with | [] -> accu | a :: q -> let t = goal_type a in let accu' = if all_guards_solved t then accu else merge_sorted accu (goal_term_uvars t) in compute_guarded_uvars1 accu' q
false
Steel.Effect.Common.fsti
Steel.Effect.Common.sorted_lists_intersect
val sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2))
val sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2))
let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> false | a1 :: q1 -> begin match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2 end
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 7, "end_line": 2903, "start_col": 0, "start_line": 2890 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved /// at a later stage to avoid overly restricting contexts of unification variables let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1) /// Solve all equalities in the list of goals by calling the F* unifier let rec solve_all_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_all_eqs (fuel - 1) | _ -> later(); solve_all_eqs (fuel - 1) /// It is important to not normalize the return_pre eqs goals before unifying /// See test7 in FramingTestSuite for a detailed explanation let rec solve_return_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> trefl(); solve_return_eqs (fuel - 1) | _ -> later(); solve_return_eqs (fuel - 1) /// Strip annotations in a goal, to get to the underlying slprop equivalence let goal_to_equiv (loc:string) : Tac unit = let t = cur_goal () in let f = term_as_formula' t in match f with | App hd0 t -> if not (is_fvar hd0 (`%squash)) then fail (loc ^ " unexpected non-squash goal in goal_to_equiv"); let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then ( apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%can_be_split_forall) then ( ignore (forall_intro ()); apply_lemma (`equiv_can_be_split) ) else if hd `is_fvar` (`%equiv_forall) then ( apply_lemma (`equiv_forall_elim); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_post) then ( apply_lemma (`can_be_split_post_elim); dismiss_slprops(); ignore (forall_intro ()); ignore (forall_intro ()) ) else if hd `is_fvar` (`%can_be_split_dep) then ( fail ("can_be_split_dep not supported in " ^ loc) ) else if hd `is_fvar` (`%can_be_split_forall_dep) then ( fail ("can_be_split_forall_dep not supported in " ^ loc) ) else // This should never happen fail (loc ^ " goal in unexpected position") | _ -> fail (loc ^ " unexpected goal") let rec term_dict_assoc (#a: Type) (key: term) (l: list (term & a)) : Tac (list a) = match l with | [] -> [] | (k, v) :: q -> let q' = term_dict_assoc key q in if k `term_eq_old` key then (v :: q') else q' /// Returns true if the goal has been solved, false if it should be delayed let solve_or_delay (dict: list (term & (unit -> Tac bool))) : Tac bool = // Beta-reduce the goal first if possible norm []; let f = term_as_formula' (cur_goal ()) in match f with | App hd0 t -> if is_fvar hd0 (`%squash) then let hd, args = collect_app t in if hd `is_fvar` (`%can_be_split) then solve_can_be_split args else if hd `is_fvar` (`%can_be_split_forall) then solve_can_be_split_forall args else if hd `is_fvar` (`%equiv_forall) then solve_equiv_forall args else if hd `is_fvar` (`%can_be_split_post) then solve_can_be_split_post args else if hd `is_fvar` (`%equiv) then solve_equiv args else if hd `is_fvar` (`%can_be_split_dep) then solve_can_be_split_dep args else if hd `is_fvar` (`%can_be_split_forall_dep) then solve_can_be_split_forall_dep args else let candidates = term_dict_assoc hd dict in let run_tac (tac: unit -> Tac bool) () : Tac bool = focus tac in begin try first (List.Tot.map run_tac candidates) with _ -> (* this is a logical goal, solve it only if it has no uvars *) if List.Tot.length (free_uvars t) = 0 then (smt (); true) else false end else // TODO: handle non-squash goals here false | Comp (Eq _) l r -> let lnbr = List.Tot.length (free_uvars l) in let rnbr = List.Tot.length (free_uvars r) in // Only solve equality if one of the terms is completely determined if lnbr = 0 || rnbr = 0 then (trefl (); true) else false | _ -> false /// Returns true if it successfully solved a goal /// If it returns false, it means it didn't find any solvable goal, /// which should mean only delayed goals are left let rec vprop_term_uvars (t:term) : Tac (list int) = match inspect_unascribe t with | Tv_Uvar i' _ -> [i'] | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits argv_uvars args else vprop_term_uvars hd | Tv_Abs _ t -> vprop_term_uvars t | _ -> [] and argv_uvars (args: list argv) : Tac (list int) = let t : unit -> Tac (list int) = fold_left (fun (n: unit -> Tac (list int)) (x, _) -> let t () : Tac (list int) = let l1 = n () in let l2 = vprop_term_uvars x in l1 `List.Tot.append` l2 in t ) (fun _ -> []) args in t () let rec remove_dups_from_sorted (#t: eqtype) (l: list t) : Tot (list t) = match l with | [] | [_] -> l | a1 :: a2 :: q -> if a1 = a2 then remove_dups_from_sorted (a2 :: q) else a1 :: remove_dups_from_sorted (a2 :: q) let simplify_list (l: list int) : Tot (list int) = remove_dups_from_sorted (List.Tot.sortWith (List.Tot.compare_of_bool (<)) l) let goal_term_uvars (t: term) : Tac (list int) = let hd, tl = collect_app t in if hd `is_fvar` (`%squash) then match tl with | [tl0, Q_Explicit] -> let _, tl1 = collect_app tl0 in simplify_list (argv_uvars tl1) | _ -> dump "ill-formed squash"; [] else [] let rec merge_sorted (l1 l2: list int) : Tot (list int) (decreases (List.Tot.length l1 + List.Tot.length l2)) = match l1 with | [] -> l2 | a1 :: q1 -> begin match l2 with | [] -> l1 | a2 :: q2 -> if a1 < a2 then a1 :: merge_sorted q1 l2 else if a2 < a1 then a2 :: merge_sorted l1 q2 else a1 :: merge_sorted q1 q2 end
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l1: Prims.list Prims.int -> l2: Prims.list Prims.int -> Prims.Tot Prims.bool
Prims.Tot
[ "total", "" ]
[]
[ "Prims.list", "Prims.int", "Prims.op_Equality", "Prims.bool", "Prims.op_LessThan", "Steel.Effect.Common.sorted_lists_intersect" ]
[ "recursion" ]
false
false
false
true
false
let rec sorted_lists_intersect (l1 l2: list int) : Tot bool (decreases (List.Tot.length l1 + List.Tot.length l2)) =
match l1 with | [] -> false | a1 :: q1 -> match l2 with | [] -> false | a2 :: q2 -> if a1 = a2 then true else if a1 < a2 then sorted_lists_intersect q1 l2 else sorted_lists_intersect l1 q2
false
Steel.Effect.Common.fsti
Steel.Effect.Common.solve_indirection_eqs
val solve_indirection_eqs (fuel: nat) : Tac unit
val solve_indirection_eqs (fuel: nat) : Tac unit
let rec solve_indirection_eqs (fuel: nat) : Tac unit = if fuel = 0 then () else match goals () with | [] -> () | hd::_ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later() else trefl(); solve_indirection_eqs (fuel - 1) | _ -> later(); solve_indirection_eqs (fuel - 1)
{ "file_name": "lib/steel/Steel.Effect.Common.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 52, "end_line": 2709, "start_col": 0, "start_line": 2698 }
(* Copyright 2020 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module Steel.Effect.Common open Steel.Memory module Mem = Steel.Memory module FExt = FStar.FunctionalExtensionality open FStar.Ghost /// This module provides various predicates and functions which are common to the /// different Steel effects. /// It also contains the tactic responsible for frame inference through a variant of AC-unification #set-options "--ide_id_info_off" (* Normalization helpers *) irreducible let framing_implicit : unit = () irreducible let __steel_reduce__ : unit = () /// An internal attribute for finer-grained normalization in framing equalities irreducible let __inner_steel_reduce__ : unit = () irreducible let __reduce__ : unit = () irreducible let smt_fallback : unit = () irreducible let ite_attr : unit = () // Needed to avoid some logical vs prop issues during unification with no subtyping [@@__steel_reduce__] unfold let true_p : prop = True module T = FStar.Tactics.V2 let join_preserves_interp (hp:slprop) (m0:hmem hp) (m1:mem{disjoint m0 m1}) : Lemma (interp hp (join m0 m1)) [SMTPat (interp hp (join m0 m1))] = let open Steel.Memory in intro_emp m1; intro_star hp emp m0 m1; affine_star hp emp (join m0 m1) (* Definition of a selector for a given slprop *) /// A selector of type `a` for a separation logic predicate hp is a function /// from a memory where the predicate hp holds, which returns a value of type `a`. /// The effect GTot indicates that selectors are ghost functions, used for specification /// and proof purposes only let selector' (a:Type0) (hp:slprop) = hmem hp -> GTot a /// Self-framing property for selectors let sel_depends_only_on (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp) (m1:mem{disjoint m0 m1}). (interp_depends_only_on hp; ( sel m0 == sel (join m0 m1))) /// Additional property that selectors must satisfy, related to internals of /// the Steel memory model encoding let sel_depends_only_on_core (#a:Type) (#hp:slprop) (sel:selector' a hp) = forall (m0:hmem hp). sel m0 == sel (core_mem m0) /// Full definition of a selector, as a function which satisfies the two predicates above let selector (a:Type) (hp:slprop) : Type = sel:selector' a hp{sel_depends_only_on sel /\ sel_depends_only_on_core sel} /// The basis of our selector framework: Separation logic assertions enhanced with selectors /// Note that selectors are "optional", it is always possible to use a non-informative selector, /// such as fun _ -> () and to rely on the standard separation logic reasoning [@@ erasable] noeq type vprop' = { hp: slprop u#1; t:Type0; sel: selector t hp} (* Lifting the star operator to an inductive type makes normalization and implementing some later functions easier *) [@@__steel_reduce__; erasable] noeq type vprop = | VUnit : vprop' -> vprop | VStar: vprop -> vprop -> vprop (* A generic lift from slprop to vprop with a non-informative selector *) [@@ __steel_reduce__] let to_vprop' (p:slprop) = {hp = p; t = unit; sel = fun _ -> ()} [@@ __steel_reduce__] unfold let to_vprop (p:slprop) = VUnit (to_vprop' p) /// Normalization steps for norm below. /// All functions marked as `unfold`, or with the `__steel_reduce__` attribute will be reduced, /// as well as some functions internal to the selector framework unfold let normal_steps = [delta_attr [`%__steel_reduce__; `%__inner_steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify] /// The core normalization primitive used to simplify Verification Conditions before encoding /// them to an SMT solver. unfold let normal (#a:Type) (x:a) = norm normal_steps x /// An abbreviation for the VStar constructor, allowing to use it with infix notation [@@ __steel_reduce__; __reduce__] let star = VStar /// Extracting the underlying separation logic assertion from a vprop [@@ __steel_reduce__] let rec hp_of (p:vprop) = match p with | VUnit p -> p.hp | VStar p1 p2 -> hp_of p1 `Mem.star` hp_of p2 /// Extracting the selector type from a vprop [@@ __steel_reduce__] let rec t_of (p:vprop) = match p with | VUnit p -> p.t | VStar p1 p2 -> t_of p1 * t_of p2 /// Extracting the selector from a vprop [@@ __steel_reduce__] let rec sel_of (p:vprop) : GTot (selector (t_of p) (hp_of p)) = match p with | VUnit p -> fun h -> p.sel h | VStar p1 p2 -> let sel1 = sel_of p1 in let sel2 = sel_of p2 in fun h -> (sel1 h, sel2 h) /// Type abbreviations for separation logic pre- and postconditions of the Steel effects type pre_t = vprop type post_t (a:Type) = a -> vprop /// An annotation to indicate which separation logic predicates correspond to monadic computations /// These computations are handled in a specific manner in the framing tactic; they correspond to places where /// the context shrinks from all local variables in the computation to variables available at the toplevel let return_pre (p:vprop) : vprop = p noextract let hmem (p:vprop) = hmem (hp_of p) /// Abstract predicate for vprop implication. Currently implemented as an implication on the underlying slprop val can_be_split (p q:pre_t) : Type0 /// Exposing the implementation of `can_be_split` when needed for proof purposes val reveal_can_be_split (_:unit) : Lemma (forall p q. can_be_split p q == Mem.slimp (hp_of p) (hp_of q)) /// A targeted version of the above val can_be_split_interp (r r':vprop) (h:hmem r) : Lemma (requires can_be_split r r') (ensures interp (hp_of r') h) /// A dependent version of can_be_split, to be applied to dependent postconditions let can_be_split_forall (#a:Type) (p q:post_t a) = forall x. can_be_split (p x) (q x) /// A version of can_be_split which is indexed by a proposition, which can be used for equalities abduction let can_be_split_dep (p:prop) (t1 t2:pre_t) = p ==> can_be_split t1 t2 /// A dependent version of the above predicate let can_be_split_forall_dep (#a:Type) (p:a -> prop) (t1 t2:post_t a) = forall (x:a). p x ==> can_be_split (t1 x) (t2 x) (* Some lemmas about the can_be_split* predicates, to be used as rewriting rules for the abstract predicates *) val can_be_split_trans (p q r:vprop) : Lemma (requires p `can_be_split` q /\ q `can_be_split` r) (ensures p `can_be_split` r) let can_be_split_trans_rev (p q r:vprop) : Lemma (requires q `can_be_split` r /\ p `can_be_split` q) (ensures p `can_be_split` r) = can_be_split_trans p q r val can_be_split_star_l (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` p) [SMTPat ((p `star` q) `can_be_split` p)] val can_be_split_star_r (p q:vprop) : Lemma (ensures (p `star` q) `can_be_split` q) [SMTPat ((p `star` q) `can_be_split` q)] val can_be_split_refl (p:vprop) : Lemma (p `can_be_split` p) [SMTPat (p `can_be_split` p)] val can_be_split_congr_l (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((p `star` r) `can_be_split` (q `star` r))) val can_be_split_congr_r (p q r: vprop) : Lemma (requires (p `can_be_split` q)) (ensures ((r `star` p) `can_be_split` (r `star` q))) let prop_and (p1 p2: prop) : Tot prop = p1 /\ p2 let can_be_split_forall_dep_trans_rev (#a: Type) (cond1 cond2: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond2 q r /\ can_be_split_forall_dep cond1 p q)) (ensures (can_be_split_forall_dep (fun x -> cond1 x `prop_and` cond2 x) p r)) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_trans x y) z) let can_be_split_forall_dep_congr_l (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> p x `star` r x) (fun x -> q x `star` r x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_l x y) z) let can_be_split_forall_dep_congr_r (#a: Type) (cond: a -> prop) (p q r: post_t a) : Lemma (requires (can_be_split_forall_dep cond p q)) (ensures (can_be_split_forall_dep cond (fun x -> r x `star` p x) (fun x -> r x `star` q x))) = Classical.forall_intro_3 (fun x y z -> Classical.move_requires (can_be_split_congr_r x y) z) /// To simplify the implementation of the framing tactic, dependent equivalence /// is defined as a double dependent implication let equiv_forall (#a:Type) (t1 t2:post_t a) : Type0 = t1 `can_be_split_forall` t2 /\ t2 `can_be_split_forall` t1 /// This equivalence models a context restriction at the end of a Steel computation; /// note that t2 does not depend on the value of type `a`, but the two vprops must be /// equivalent let can_be_split_post (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) = forall (x:a). equiv_forall (t1 x) t2 /// Lifting the equivalence relation to vprops. Two vprops are equivalent if the underlying slprops /// are equivalent val equiv (p q:vprop) : prop /// Revealing the definition of vprop equivalence when needed for proof purposes. /// In other cases, the predicate is abstract val reveal_equiv (p q:vprop) : Lemma (p `equiv` q <==> hp_of p `Mem.equiv` hp_of q) (* A restricted view of the heap, that only allows to access selectors of the current slprop *) let rmem' (pre:vprop) = FExt.restricted_g_t (r0:vprop{can_be_split pre r0}) (fun r0 -> normal (t_of r0)) /// Ensuring that rmems encapsulate the structure induced by the separation logic star val valid_rmem (#frame:vprop) (h:rmem' frame) : prop unfold let rmem (pre:vprop) = h:rmem' pre{valid_rmem h} /// Exposing the definition of mk_rmem to better normalize Steel VCs unfold noextract let unrestricted_mk_rmem (r:vprop) (h:hmem r) = fun (r0:vprop{r `can_be_split` r0}) -> can_be_split_interp r r0 h; sel_of r0 h [@@ __inner_steel_reduce__] noextract let mk_rmem' (r:vprop) (h:hmem r) : Tot (rmem' r) = FExt.on_dom_g (r0:vprop{r `can_be_split` r0}) (unrestricted_mk_rmem r h) val lemma_valid_mk_rmem (r:vprop) (h:hmem r) : Lemma (valid_rmem (mk_rmem' r h)) [@@ __inner_steel_reduce__] noextract let mk_rmem (r:vprop) (h:hmem r) : Tot (rmem r) = lemma_valid_mk_rmem r h; mk_rmem' r h val reveal_mk_rmem (r:vprop) (h:hmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (ensures reveal_can_be_split(); (mk_rmem r h) r0 == sel_of r0 h) (* Logical pre and postconditions can only access the restricted view of the heap *) type req_t (pre:pre_t) = rmem pre -> Type0 type ens_t (pre:pre_t) (a:Type) (post:post_t a) = rmem pre -> (x:a) -> rmem (post x) -> Type0 (* Empty assertion *) val emp : vprop /// When needed for proof purposes, the empty assertion is a direct lift of the /// empty assertion from Steel.Memory val reveal_emp (_:unit) : Lemma (hp_of emp == Mem.emp /\ t_of emp == unit) /// Lifting pure predicates to vprop [@@__steel_reduce__] unfold let pure (p:prop) = to_vprop (pure p) /// Framing predicates for the Steel effect. If the current computation has already /// been framed, then the additional frame is the empty predicate let maybe_emp (framed:bool) (frame:pre_t) = if framed then frame == emp else True /// Dependent version of the above predicate, usable in dependent postconditions let maybe_emp_dep (#a:Type) (framed:bool) (frame:post_t a) = if framed then (forall x. frame x == emp) else True (* focus_rmem is an additional restriction of our view of memory. We expose it here to be able to reduce through normalization; Any valid application of focus_rmem h will be reduced to the application of h *) [@@ __steel_reduce__] unfold let unrestricted_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) = fun (r':vprop{can_be_split r0 r'}) -> can_be_split_trans r r0 r'; h r' [@@ __inner_steel_reduce__] let focus_rmem' (#r: vprop) (h: rmem r) (r0: vprop{r `can_be_split` r0}) : Tot (rmem' r0) = FExt.on_dom_g (r':vprop{can_be_split r0 r'}) (unrestricted_focus_rmem h r0) val lemma_valid_focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Lemma (valid_rmem (focus_rmem' h r0)) [@@ __inner_steel_reduce__] let focus_rmem (#r:vprop) (h:rmem r) (r0:vprop{r `can_be_split` r0}) : Tot (rmem r0) = lemma_valid_focus_rmem h r0; focus_rmem' h r0 /// Exposing that calling focus_rmem on the current context corresponds to an equality let focus_rmem_refl (r:vprop) (h:rmem r) : Lemma (focus_rmem #r h r == h) = FStar.FunctionalExtensionality.extensionality_g _ _ (focus_rmem #r h r) h open FStar.Tactics.V2 /// State that all "atomic" subresources have the same selectors on both views. /// The predicate has the __steel_reduce__ attribute, ensuring that VC normalization /// will reduce it to a conjunction of equalities on atomic subresources /// This predicate is also marked as `strict_on_arguments` on [frame], ensuring that /// it will not be reduced when the frame is symbolic /// Instead, the predicate will be rewritten to an equality using `lemma_frame_equalities` below [@@ __steel_reduce__; strict_on_arguments [0]] let rec frame_equalities' (frame:vprop) (h0:rmem frame) (h1:rmem frame) : Type0 = begin match frame with | VUnit p -> h0 frame == h1 frame | VStar p1 p2 -> can_be_split_star_l p1 p2; can_be_split_star_r p1 p2; let h01 = focus_rmem h0 p1 in let h11 = focus_rmem h1 p1 in let h02 = focus_rmem h0 p2 in let h12 = focus_rmem h1 p2 in frame_equalities' p1 h01 h11 /\ frame_equalities' p2 h02 h12 end /// This lemma states that frame_equalities is the same as an equality on the top-level frame. /// The uncommon formulation with an extra [p] is needed to use in `rewrite_with_tactic`, /// where the goal is of the shape `frame_equalities frame h0 h1 == ?u` /// The rewriting happens below, in `frame_vc_norm` val lemma_frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) (p:Type0) : Lemma (requires (h0 frame == h1 frame) == p) (ensures frame_equalities' frame h0 h1 == p) /// A special case for frames about emp. val lemma_frame_emp (h0:rmem emp) (h1:rmem emp) (p:Type0) : Lemma (requires True == p) (ensures frame_equalities' emp h0 h1 == p) /// A variant of conjunction elimination, suitable to the equality goals during rewriting val elim_conjunction (p1 p1' p2 p2':Type0) : Lemma (requires p1 == p1' /\ p2 == p2') (ensures (p1 /\ p2) == (p1' /\ p2')) /// Normalization and rewriting step for generating frame equalities. /// The frame_equalities function has the strict_on_arguments attribute on the [frame], /// ensuring that it is not reduced when the frame is symbolic. /// When that happens, we want to replace frame_equalities by an equality on the frame, /// mimicking reduction [@@plugin] let frame_vc_norm () : Tac unit = with_compat_pre_core 0 (fun _ -> // Do not normalize mk_rmem/focus_rmem to simplify application of // the reflexivity lemma on frame_equalities' norm [delta_attr [`%__steel_reduce__]; delta_only [`%Mkvprop'?.t; `%Mkvprop'?.hp; `%Mkvprop'?.sel; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit]; delta_qualifier ["unfold"]; iota;zeta;primops; simplify]; // After reduction, the term to rewrite might be of the shape // (frame_equalities' ... /\ frame_equalities' .. /\ ...) == ?u, // with some frame_equalities' possibly already fully reduced // We repeatedly split the clause and extract the term on the left // to generate equalities on atomic subresources ignore (repeat (fun _ -> // Try to split the conjunction. If there is no conjunction, we exit the repeat apply_lemma (`elim_conjunction); // Dismiss the two uvars created for the RHS, they'll be solved by unification dismiss (); dismiss (); // The first goal is the left conjunction split (); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // Rewrites the frame_equalities if it wasn't yet reduced or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; // Finally solve the uvar, finishing the rewriting for this clause trefl () )); // Removes the frame equality if it is about emp or_else (fun _ -> apply_lemma (`lemma_frame_emp); dismiss()) (fun _ -> ()); // We do not have conjunctions anymore, we try to apply the frame_equalities rewriting // If it fails, the frame was not symbolic, so there is nothing to do or_else (fun _ -> apply_lemma (`lemma_frame_equalities); dismiss ()) (fun _ -> ()); norm normal_steps; trefl ()) [@@ __steel_reduce__] unfold let frame_equalities (frame:vprop) (h0:rmem frame) (h1:rmem frame) : prop = rewrite_with_tactic frame_vc_norm (frame_equalities' frame h0 h1) /// More lemmas about the abstract can_be_split predicates, to be used as /// rewriting rules in the tactic below val can_be_split_dep_refl (p:vprop) : Lemma (can_be_split_dep true_p p p) val equiv_can_be_split (p1 p2:vprop) : Lemma (requires p1 `equiv` p2) (ensures p1 `can_be_split` p2) val intro_can_be_split_frame (p q:vprop) (frame:vprop) : Lemma (requires q `equiv` (p `star` frame)) (ensures can_be_split q p /\ True) val can_be_split_post_elim (#a #b:Type) (t1:a -> post_t b) (t2:post_t b) : Lemma (requires (forall (x:a) (y:b). t1 x y `equiv` t2 y)) (ensures t1 `can_be_split_post` t2) val equiv_forall_refl (#a:Type) (t:post_t a) : Lemma (t `equiv_forall` t) val equiv_forall_elim (#a:Type) (t1 t2:post_t a) : Lemma (requires (forall (x:a). t1 x `equiv` t2 x)) (ensures t1 `equiv_forall` t2) open FStar.Tactics.CanonCommMonoidSimple.Equiv (* equiv is an equivalence relation on vprops *) /// Lemmas establishing the equivalence properties on equiv val equiv_refl (x:vprop) : Lemma (equiv x x) val equiv_sym (x y:vprop) : Lemma (requires equiv x y) (ensures equiv y x) val equiv_trans (x y z:vprop) : Lemma (requires equiv x y /\ equiv y z) (ensures equiv x z) module CE = FStar.Algebra.CommMonoid.Equiv /// Equiv is an equivalence relation for vprops elements inline_for_extraction noextract let req : CE.equiv vprop = CE.EQ equiv equiv_refl equiv_sym equiv_trans (* Star induces a commutative monoid for the equiv equivalence relation *) /// Lemmas establishing the commutative monoid properties val cm_identity (x:vprop) : Lemma ((emp `star` x) `equiv` x) val star_commutative (p1 p2:vprop) : Lemma ((p1 `star` p2) `equiv` (p2 `star` p1)) val star_associative (p1 p2 p3:vprop) : Lemma (((p1 `star` p2) `star` p3) `equiv` (p1 `star` (p2 `star` p3))) val star_congruence (p1 p2 p3 p4:vprop) : Lemma (requires p1 `equiv` p3 /\ p2 `equiv` p4) (ensures (p1 `star` p2) `equiv` (p3 `star` p4)) /// Star induces a commutative monoid on vprops [@__steel_reduce__] inline_for_extraction noextract let rm : CE.cm vprop req = CE.CM emp star cm_identity star_associative star_commutative star_congruence (*** Vprop combinators ***) (* Refining a vprop with a selector predicate *) /// Separation logic predicate stating the validity of a vprop with an additional refinement on its selector val vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vrefine_hp (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: mem) : Lemma (interp (vrefine_hp v p) m <==> (interp (hp_of v) m /\ p (sel_of v m))) /// Selector type for a refined vprop [@__steel_reduce__] let vrefine_t (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot Type = (x: t_of v {p x}) /// Selector of a refined vprop. Returns a value which satisfies the refinement predicate val vrefine_sel (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot (selector (vrefine_t v p) (vrefine_hp v p)) /// Exposing the definition of the refined selector val vrefine_sel_eq (v: vprop) (p: (normal (t_of v) -> Tot prop)) (m: Mem.hmem (vrefine_hp v p)) : Lemma ( interp (hp_of v) m /\ vrefine_sel v p m == sel_of v m ) // [SMTPat ((vrefine_sel v p) m)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above pieces to define a vprop refined by a selector prediacte [@__steel_reduce__] let vrefine' (v: vprop) (p: (normal (t_of v) -> Tot prop)) : Tot vprop' = { hp = vrefine_hp v p; t = vrefine_t v p; sel = vrefine_sel v p; } [@__steel_reduce__] let vrefine (v: vprop) (p: (normal (t_of v) -> Tot prop)) = VUnit (vrefine' v p) (* Dependent star for vprops *) /// Separation logic predicate corresponding to a dependent star, /// where the second predicate depends on the selector value of the first val vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (slprop u#1) /// Exposing the validity of the above predicate when needed for proof purposes val interp_vdep_hp (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: mem) : Lemma (interp (vdep_hp v p) m <==> (interp (hp_of v) m /\ interp (hp_of v `Mem.star` hp_of (p (sel_of v m))) m)) /// Helper to define the selector type of the second component of the dependent star let vdep_payload (v: vprop) (p: ( (t_of v) -> Tot vprop)) (x: t_of v) : Tot Type = t_of (p x) /// Selector type for the dependent star: A dependent tuple, where the second component's type depends on the first vprop let vdep_t (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot Type = dtuple2 (t_of v) (vdep_payload v p) /// Selector for the dependent star val vdep_sel (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot (selector (vdep_t v p) (vdep_hp v p)) /// Exposing the definition of the dependent star's selector when needed for proof purposes val vdep_sel_eq (v: vprop) (p: ( (t_of v) -> Tot vprop)) (m: Mem.hmem (vdep_hp v p)) : Lemma ( interp (hp_of v) m /\ begin let x = sel_of v m in interp (hp_of (p x)) m /\ vdep_sel v p m == (| x, sel_of (p x) m |) end ) /// Combining the elements above to create a dependent star vprop [@__steel_reduce__] let vdep' (v: vprop) (p: ( (t_of v) -> Tot vprop)) : Tot vprop' = { hp = vdep_hp v p; t = vdep_t v p; sel = vdep_sel v p; } [@__steel_reduce__] let vdep (v: vprop) (p: ( (t_of v) -> Tot vprop)) = VUnit (vdep' v p) (* Selector rewrite combinator *) /// The selector of a rewrite combinator applies a function `f` to the current selector of a vprop. val vrewrite_sel (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot (selector t (normal (hp_of v))) /// Exposing the definition of the above selector val vrewrite_sel_eq (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) (h: Mem.hmem (normal (hp_of v))) : Lemma ((vrewrite_sel v f <: selector' _ _) h == f ((normal (sel_of v) <: selector' _ _) h)) // [SMTPat (vrewrite_sel v f h)] // FIXME: this pattern causes Z3 "wrong number of argument" errors /// Combining the above elements to create a rewrite vprop [@__steel_reduce__] let vrewrite' (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop' = { hp = normal (hp_of v); t = t; sel = vrewrite_sel v f; } [@__steel_reduce__] let vrewrite (v: vprop) (#t: Type) (f: (normal (t_of v) -> GTot t)) : Tot vprop = VUnit (vrewrite' v f) (*** Framing tactic ***) (* Specialize visit_tm from the standard F* tactic library to reimplement name_appears_in. AF: As of Jan 14, 2021, calling name_appears_in from FStar.Tactics.Derived leads to a segfault *) exception Appears let on_sort_binder (f : term -> Tac unit) (b:binder) : Tac unit = f b.sort let rec visit_tm (ff : term -> Tac unit) (t : term) : Tac unit = let tv = inspect t in (match tv with | Tv_FVar _ | Tv_UInst _ _ | Tv_Var _ | Tv_BVar _ -> () | Tv_Type _ -> () | Tv_Const c -> () | Tv_Uvar i u -> () | Tv_Unsupp -> () | Tv_Unknown -> () | Tv_Arrow b c -> on_sort_binder ff b; visit_comp ff c | Tv_Abs b t -> let b = on_sort_binder (visit_tm ff) b in visit_tm ff t | Tv_App l (r, q) -> visit_tm ff l; visit_tm ff r | Tv_Refine b r -> on_sort_binder ff b; visit_tm ff r | Tv_Let r attrs b def t -> on_sort_binder ff b; visit_tm ff def; visit_tm ff t | Tv_Match sc _ brs -> visit_tm ff sc; iter (visit_br ff) brs | Tv_AscribedT e t topt _ -> visit_tm ff e; visit_tm ff t | Tv_AscribedC e c topt _ -> visit_tm ff e ); ff t and visit_br (ff : term -> Tac unit) (b:branch) : Tac unit = let (p, t) = b in visit_tm ff t and visit_comp (ff : term -> Tac unit) (c : comp) : Tac unit = let cv = inspect_comp c in match cv with | C_Total ret -> visit_tm ff ret | C_GTotal ret -> visit_tm ff ret | C_Lemma pre post pats -> visit_tm ff pre; visit_tm ff post; visit_tm ff pats | C_Eff us eff res args decrs -> visit_tm ff res; iter (fun (a, q) -> visit_tm ff a) args; iter (visit_tm ff) decrs /// Decides whether a top-level name [nm] syntactically /// appears in the term [t]. let name_appears_in (nm:name) (t:term) : Tac bool = let ff (t : term) : Tac unit = match inspect t with | Tv_FVar fv -> if inspect_fv fv = nm then raise Appears | t -> () in try ignore (visit_tm ff t); false with | Appears -> true | e -> raise e /// Checks whether term [t] appears in term [i] let term_appears_in (t:term) (i:term) : Tac bool = name_appears_in (explode_qn (term_to_string t)) i /// We define a small language to handle arbitrary separation logic predicates. /// Separation logic predicates are encoded as atoms for which equality is decidable, /// here represented as integers let atom : eqtype = int let rec atoms_to_string (l:list atom) = match l with | [] -> "" | hd::tl -> string_of_int hd ^ " " ^ atoms_to_string tl /// Reflecting the structure of our separation logic on atmos type exp : Type = | Unit : exp | Mult : exp -> exp -> exp | Atom : atom -> exp /// A map from atoms to the terms they represent. /// The second component of the term corresponds to a default element, /// ensuring we never raise an exception when trying to access an element in the map let amap (a:Type) = list (atom * a) * a /// An empty atom map: The list map is empty let const (#a:Type) (xa:a) : amap a = ([], xa) /// Accessing an element in the atom map // We reimplement List.Tot.Base.assoc because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_assoc (#key: eqtype) (#value: Type) (k: key) (dict: list (key & value)) : Pure (option value) (requires True) (ensures (fun res -> res == List.Tot.assoc k dict)) = match dict with | [] -> None | (k', v') :: q -> if k = k' then Some v' else my_assoc k q let select (#a:Type) (x:atom) (am:amap a) : Tot a = match my_assoc #atom #a x (fst am) with | Some a -> a | _ -> snd am /// Updating the atom map. Since select finds the first element corresponding to /// the atom in the list and we do not have any remove function, /// we can simply append the new element at the head without removing any possible /// previous element let update (#a:Type) (x:atom) (xa:a) (am:amap a) : amap a = (x, xa)::fst am, snd am /// Check whether the current term is an unresolved vprop unification variable. /// This can happen if either it is a uvar, or it is an unresolved dependent /// vprop uvar which is applied to some argument let is_uvar (t:term) : Tac bool = match inspect t with | Tv_Uvar _ _ -> true | Tv_App _ _ -> let hd, args = collect_app t in Tv_Uvar? (inspect hd) | _ -> false /// For a given term t, collect all terms in the list l with the same head symbol let rec get_candidates (t:term) (l:list term) : Tac (list term) = let name, _ = collect_app t in match l with | [] -> [] | hd::tl -> let n, _ = collect_app hd in if term_eq_old n name then ( hd::(get_candidates t tl) ) else get_candidates t tl /// Try to remove a term that is exactly matching, not just that can be unified let rec trivial_cancel (t:atom) (l:list atom) = match l with | [] -> false, l | hd::tl -> if hd = t then // These elements match, we remove them true, tl else (let b, res = trivial_cancel t tl in b, hd::res) /// Call trivial_cancel on all elements of l1. /// The first two lists returned are the remainders of l1 and l2. /// The last two lists are the removed parts of l1 and l2, with /// the additional invariant that they are equal let rec trivial_cancels (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, [], [] | hd::tl -> let b, l2' = trivial_cancel hd l2 in let l1', l2', l1_del, l2_del = trivial_cancels tl l2' am in (if b then l1' else hd::l1'), l2', (if b then hd::l1_del else l1_del), (if b then hd::l2_del else l2_del) exception Failed exception Success /// Helper to print the terms corresponding to the current list of atoms let rec print_atoms (l:list atom) (am:amap term) : Tac string = match l with | [] -> "" | [hd] -> term_to_string (select hd am) | hd::tl -> term_to_string (select hd am) ^ " * " ^ print_atoms tl am /// For a list of candidates l, count the number that can unify with t. /// Does not try to unify with a uvar, this will be done at the very end. /// Tries to unify with slprops with a different head symbol, it might /// be an abbreviation let rec try_candidates (t:atom) (l:list atom) (am:amap term) : Tac (atom * int) = match l with | [] -> t, 0 | hd::tl -> if is_uvar (select hd am) then (try_candidates t tl am) else // Encapsulate unify in a try/with to ensure unification is not actually performed let res = try if unify (select t am) (select hd am) then raise Success else raise Failed with | Success -> true | _ -> false in let t', n' = try_candidates t tl am in if res && hd <> t' then hd, 1 + n' else t', n' /// Remove the given term from the list. Only to be called when /// try_candidates succeeded let rec remove_from_list (t:atom) (l:list atom) : Tac (list atom) = match l with | [] -> fail "atom in remove_from_list not found: should not happen"; [] | hd::tl -> if t = hd then tl else hd::remove_from_list t tl /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) let rec equivalent_lists_once (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l1 with | [] -> [], l2, l1_del, l2_del | hd::tl -> let t, n = try_candidates hd l2 am in if n = 1 then ( let l2 = remove_from_list t l2 in equivalent_lists_once tl l2 (hd::l1_del) (t::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once tl l2 l1_del l2_del am in hd::rem1, rem2, l1'_del, l2'_del ) /// Check if two lists of slprops are equivalent by recursively calling /// try_candidates by iterating on l2. /// Assumes that only l2 contains terms with the head symbol unresolved. /// It returns all elements that were not resolved during this iteration *) /// This is very close to equivalent_lists_once above, but helps making progress /// when l1 contains syntactically equal candidates let rec equivalent_lists_once_l2 (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * list atom * list atom) = match l2 with | [] -> l1, [], l1_del, l2_del | hd::tl -> if is_uvar (select hd am) then // We do not try to match the vprop uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del else ( let t, n = try_candidates hd l1 am in if n = 1 then ( let l1 = remove_from_list t l1 in equivalent_lists_once_l2 l1 tl (t::l1_del) (hd::l2_del) am ) else ( // Either too many candidates for this scrutinee, or no candidate but the uvar let rem1, rem2, l1'_del, l2'_del = equivalent_lists_once_l2 l1 tl l1_del l2_del am in rem1, hd::rem2, l1'_del, l2'_del ) ) let get_head (l:list atom) (am:amap term) : term = match l with | [] -> `() | hd::_ -> select hd am /// Checks whether the list of atoms [l] only contains one unresolved uvar let is_only_uvar (l:list atom) (am:amap term) : Tac bool = if List.Tot.Base.length l = 1 then is_uvar (select (List.Tot.Base.hd l) am) else false /// Assumes that u is a uvar, checks that all variables in l can be unified with it. /// Later in the tactic, the uvar will be unified to a star of l *) let rec try_unifying_remaining (l:list atom) (u:term) (am:amap term) : Tac unit = match l with | [] -> () | hd::tl -> try if unify u (select hd am) then raise Success else raise Failed with | Success -> try_unifying_remaining tl u am | _ -> fail ("could not find candidate for scrutinee " ^ term_to_string (select hd am)) /// Is SMT rewriting enabled for this binder let is_smt_binder (b:binder) : Tac bool = let l = b.attrs in not (List.Tot.isEmpty (filter (fun t -> is_fvar t (`%smt_fallback)) l)) /// Creates a new term, where all arguments where SMT rewriting is enabled have been replaced /// by fresh, unconstrained unification variables let rec new_args_for_smt_attrs (env:env) (l:list argv) (ty:typ) : Tac (list argv * list term) = let fresh_ghost_uvar ty = let e = cur_env () in ghost_uvar_env e ty in match l, inspect_unascribe ty with | (arg, aqualv)::tl, Tv_Arrow binder comp -> let needs_smt = is_smt_binder binder in let new_hd = if needs_smt then ( let arg_ty = tc env arg in let uvar = fresh_ghost_uvar arg_ty in unshelve uvar; flip (); (uvar, aqualv) ) else (arg, aqualv) in begin let ty2 = match inspect_comp comp with | C_Total ty2 -> ty2 | C_Eff _ eff_name ty2 _ _ -> if eff_name = ["Prims"; "Tot"] then ty2 else fail "computation type not supported in definition of slprops" | _ -> fail "computation type not supported in definition of slprops" in let tl_argv, tl_terms = new_args_for_smt_attrs env tl ty2 in new_hd::tl_argv, (if needs_smt then arg::tl_terms else tl_terms) end | [], Tv_FVar fv -> [], [] | _ -> fail "should not happen. Is an slprop partially applied?" /// Rewrites all terms in the context to enable SMT rewriting through the use of fresh, unconstrained unification variables let rewrite_term_for_smt (env:env) (am:amap term * list term) (a:atom) : Tac (amap term * list term) = let am, prev_uvar_terms = am in let term = select a am in let hd, args = collect_app term in let t = tc env hd in let new_args, uvar_terms = new_args_for_smt_attrs env args t in let new_term = mk_app hd new_args in update a new_term am, List.Tot.append uvar_terms prev_uvar_terms /// User-facing error message when the framing tactic fails let fail_atoms (#a:Type) (l1 l2:list atom) (am:amap term) : Tac a = fail ("could not find a solution for unifying\n" ^ print_atoms l1 am ^ "\nand\n" ^ print_atoms l2 am) /// Variant of equivalent_lists' below to be called once terms have been rewritten to allow SMT rewriting. /// If unification succeeds and we have unicity of the solution, this tactic will succeed, /// and ultimately create an SMT guard that the two terms are actually equal let rec equivalent_lists_fallback (n:nat) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true)) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then // Should always be smaller or equal to n // If it is equal, no progress was made. fail_atoms rem1 rem2 am else equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' am /// Iterates over all terms in [l2] to prepare them for unification with SMT rewriting let replace_smt_uvars (l1 l2:list atom) (am:amap term) : Tac (amap term * list term) = let env = cur_env () in fold_left (rewrite_term_for_smt env) (am, []) l2 /// Recursively calls equivalent_lists_once. /// Stops when we're done with unification, or when we didn't make any progress /// If we didn't make any progress, we have too many candidates for some terms. /// Accumulates rewritings of l1 and l2 in l1_del and l2_del, with the invariant /// that the two lists are unifiable at any point /// The boolean indicates if there is a leftover empty frame let rec equivalent_lists' (n:nat) (use_smt:bool) (l1 l2 l1_del l2_del:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = match l1 with | [] -> begin match l2 with | [] -> (l1_del, l2_del, false, []) | [hd] -> // Succeed if there is only one uvar left in l2, which can be therefore // be unified with emp if is_uvar (select hd am) then ( // xsdenote is left associative: We put hd at the top to get // ?u `star` p <==> emp `star` p (l1_del, hd :: l2_del, true, [])) else fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) | _ -> fail ("could not find candidates for " ^ term_to_string (get_head l2 am)) end | _ -> if is_only_uvar l2 am then ( // Terms left in l1, but only a uvar left in l2. // Put all terms left at the end of l1_rem, so that they can be unified // with exactly the uvar because of the structure of xsdenote try_unifying_remaining l1 (get_head l2 am) am; l1_del `List.Tot.append` l1, l2_del `List.Tot.append` l2, false, [] ) else let rem1, rem2, l1_del', l2_del' = equivalent_lists_once l1 l2 l1_del l2_del am in let n' = List.Tot.length rem1 in if n' >= n then ( // Try to make progress by matching non-uvars of l2 with candidates in l1 let rem1, rem2, l1_del', l2_del' = equivalent_lists_once_l2 rem1 rem2 l1_del' l2_del' am in let n' = List.Tot.length rem1 in if n' >= n then ( // Should always be smaller or equal to n // If it is equal, no progress was made. if use_smt then // SMT fallback is allowed let new_am, uvar_terms = replace_smt_uvars rem1 rem2 am in let l1_f, l2_f, b = equivalent_lists_fallback n' rem1 rem2 l1_del' l2_del' new_am in l1_f, l2_f, b, uvar_terms else fail_atoms rem1 rem2 am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am ) else equivalent_lists' n' use_smt rem1 rem2 l1_del' l2_del' am /// Checks if term for atom t unifies with fall uvars in l let rec unifies_with_all_uvars (t:term) (l:list atom) (am:amap term) : Tac bool = match l with | [] -> true | hd::tl -> if unifies_with_all_uvars t tl am then ( // Unified with tail, try this term let hd_t = select hd am in if is_uvar hd_t then ( // The head term is a uvar, try unifying try if unify t hd_t then raise Success else raise Failed with | Success -> true | _ -> false ) else true // The uvar is not a head term, we do not need to try it ) else false /// Puts all terms in l1 that cannot unify with the uvars in l2 at the top: /// They need to be solved first let rec most_restricted_at_top (l1 l2:list atom) (am:amap term) : Tac (list atom) = match l1 with | [] -> [] | hd::tl -> if unifies_with_all_uvars (select hd am) l2 am then (most_restricted_at_top tl l2 am) `List.Tot.append` [hd] else hd::(most_restricted_at_top tl l2 am) /// Core AC-unification tactic. /// First remove all trivially equal terms, then try to decide equivalence. /// Assumes that l1 does not contain any vprop uvar. /// If it succeeds, returns permutations of l1, l2, and a boolean indicating /// if l2 has a trailing empty frame to be unified let equivalent_lists (use_smt:bool) (l1 l2:list atom) (am:amap term) : Tac (list atom * list atom * bool * list term) = let l1, l2, l1_del, l2_del = trivial_cancels l1 l2 am in let l1 = most_restricted_at_top l1 l2 am in let n = List.Tot.length l1 in let l1_del, l2_del, emp_frame, uvar_terms = equivalent_lists' n use_smt l1 l2 l1_del l2_del am in l1_del, l2_del, emp_frame, uvar_terms (* Helpers to relate the actual terms to their representation as a list of atoms *) open FStar.Reflection.V2.Derived.Lemmas let rec list_to_string (l:list term) : Tac string = match l with | [] -> "end" | hd::tl -> term_to_string hd ^ " " ^ list_to_string tl let rec mdenote_gen (#a:Type u#aa) (unit:a) (mult:a -> a -> a) (am:amap a) (e:exp) : a = match e with | Unit -> unit | Atom x -> select x am | Mult e1 e2 -> mult (mdenote_gen unit mult am e1) (mdenote_gen unit mult am e2) let rec xsdenote_gen (#a:Type) (unit:a) (mult:a -> a -> a) (am:amap a) (xs:list atom) : a = match xs with | [] -> unit | [x] -> select x am | x::xs' -> mult (select x am) (xsdenote_gen unit mult am xs') unfold let mdenote (#a:Type u#aa) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : a = let open FStar.Algebra.CommMonoid.Equiv in mdenote_gen (CM?.unit m) (CM?.mult m) am e unfold let xsdenote (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : a = let open FStar.Algebra.CommMonoid.Equiv in xsdenote_gen (CM?.unit m) (CM?.mult m) am xs // We reimplement List.Tot.Base.append because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_append (#t: Type) (l1 l2: list t) : Pure (list t) (requires True) (ensures (fun res -> res == l1 `List.Tot.append` l2)) (decreases l1) = match l1 with | [] -> l2 | a :: q -> a :: my_append q l2 let rec flatten (e:exp) : list atom = match e with | Unit -> [] | Atom x -> [x] | Mult e1 e2 -> flatten e1 `my_append` flatten e2 let rec flatten_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs1 xs2:list atom) : Lemma (xsdenote eq m am (xs1 `my_append` xs2) `CE.EQ?.eq eq` CE.CM?.mult m (xsdenote eq m am xs1) (xsdenote eq m am xs2)) = let open FStar.Algebra.CommMonoid.Equiv in match xs1 with | [] -> CM?.identity m (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.unit m) (xsdenote eq m am xs2)) (xsdenote eq m am xs2) | [x] -> ( if (Nil? xs2) then (right_identity eq m (select x am); EQ?.symmetry eq (CM?.mult m (select x am) (CM?.unit m)) (select x am)) else EQ?.reflexivity eq (CM?.mult m (xsdenote eq m am [x]) (xsdenote eq m am xs2))) | x::xs1' -> flatten_correct_aux eq m am xs1' xs2; EQ?.reflexivity eq (select x am); CM?.congruence m (select x am) (xsdenote eq m am (xs1' `my_append` xs2)) (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2)); CM?.associativity m (select x am) (xsdenote eq m am xs1') (xsdenote eq m am xs2); EQ?.symmetry eq (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))); EQ?.transitivity eq (CM?.mult m (select x am) (xsdenote eq m am (xs1' `my_append` xs2))) (CM?.mult m (select x am) (CM?.mult m (xsdenote eq m am xs1') (xsdenote eq m am xs2))) (CM?.mult m (CM?.mult m (select x am) (xsdenote eq m am xs1')) (xsdenote eq m am xs2)) let rec flatten_correct (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e:exp) : Lemma (mdenote eq m am e `CE.EQ?.eq eq` xsdenote eq m am (flatten e)) = let open FStar.Algebra.CommMonoid.Equiv in match e with | Unit -> EQ?.reflexivity eq (CM?.unit m) | Atom x -> EQ?.reflexivity eq (select x am) | Mult e1 e2 -> flatten_correct_aux eq m am (flatten e1) (flatten e2); EQ?.symmetry eq (xsdenote eq m am (flatten e1 `my_append` flatten e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))); flatten_correct eq m am e1; flatten_correct eq m am e2; CM?.congruence m (mdenote eq m am e1) (mdenote eq m am e2) (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)); EQ?.transitivity eq (CM?.mult m (mdenote eq m am e1) (mdenote eq m am e2)) (CM?.mult m (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2))) (xsdenote eq m am (flatten e1 `my_append` flatten e2)) let monoid_reflect (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (e1 e2:exp) (_ : squash (xsdenote eq m am (flatten e1) `CE.EQ?.eq eq` xsdenote eq m am (flatten e2))) : squash (mdenote eq m am e1 `CE.EQ?.eq eq` mdenote eq m am e2) = flatten_correct eq m am e1; flatten_correct eq m am e2; CE.EQ?.symmetry eq (mdenote eq m am e2) (xsdenote eq m am (flatten e2)); CE.EQ?.transitivity eq (xsdenote eq m am (flatten e1)) (xsdenote eq m am (flatten e2)) (mdenote eq m am e2); CE.EQ?.transitivity eq (mdenote eq m am e1) (xsdenote eq m am (flatten e1)) (mdenote eq m am e2) // Here we sort the variable numbers // We reimplement List.Tot.Base.sortWith because we need our tactic to normalize it, // but we don't want to normalize user-provided instances let rec my_partition (#a: Type) (f: (a -> Tot bool)) (l: list a) : Pure (list a & list a) (requires True) (ensures (fun res -> res == List.Tot.partition f l)) = match l with | [] -> [], [] | hd::tl -> let l1, l2 = my_partition f tl in if f hd then hd::l1, l2 else l1, hd::l2 let rec partition_ext (#a: Type) (f1 f2: (a -> Tot bool)) (l: list a) : Lemma (requires (forall x . f1 x == f2 x)) (ensures (List.Tot.partition f1 l == List.Tot.partition f2 l)) = match l with | [] -> () | hd::tl -> partition_ext f1 f2 tl let my_bool_of_compare (#a: Type) (f: a -> a -> Tot int) (x: a) (y: a) : Tot bool = f x y < 0 let rec my_sortWith (#a: Type) (f: (a -> a -> Tot int)) (l:list a) : Pure (list a) (requires True) (ensures (fun res -> res == List.Tot.sortWith f l)) (decreases (List.Tot.length l)) = match l with | [] -> [] | pivot::tl -> let hi, lo = my_partition (my_bool_of_compare f pivot) tl in partition_ext (my_bool_of_compare f pivot) (List.Tot.bool_of_compare f pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f pivot) tl; my_append (my_sortWith f lo) (pivot::my_sortWith f hi) let rec sortWith_ext (#a: Type) (f1 f2: (a -> a -> Tot int)) (l: list a) : Lemma (requires (forall x y . f1 x y == f2 x y)) (ensures (List.Tot.sortWith f1 l == List.Tot.sortWith f2 l)) (decreases (List.Tot.length l)) = match l with | [] -> () | pivot::tl -> partition_ext (List.Tot.bool_of_compare f1 pivot) (List.Tot.bool_of_compare f2 pivot) tl; List.Tot.partition_length (List.Tot.bool_of_compare f1 pivot) tl; let hi, lo = List.Tot.partition (List.Tot.bool_of_compare f1 pivot) tl in sortWith_ext f1 f2 lo; sortWith_ext f1 f2 hi let permute = list atom -> list atom let my_compare_of_bool (#a:eqtype) (rel: a -> a -> Tot bool) (x: a) (y: a) : Tot int = if x `rel` y then -1 else if x = y then 0 else 1 let sort : permute = my_sortWith #int (my_compare_of_bool (<)) #push-options "--fuel 1 --ifuel 1" let lemma_xsdenote_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (hd:atom) (tl:list atom) : Lemma (xsdenote eq m am (hd::tl) `CE.EQ?.eq eq` (CE.CM?.mult m (select hd am) (xsdenote eq m am tl))) = let open FStar.Algebra.CommMonoid.Equiv in match tl with | [] -> assert (xsdenote eq m am (hd::tl) == select hd am); CM?.identity m (select hd am); EQ?.symmetry eq (CM?.unit m `CM?.mult m` select hd am) (select hd am); CM?.commutativity m (CM?.unit m) (select hd am); EQ?.transitivity eq (xsdenote eq m am (hd::tl)) (CM?.unit m `CM?.mult m` select hd am) (CM?.mult m (select hd am) (xsdenote eq m am tl)) | _ -> EQ?.reflexivity eq (xsdenote eq m am (hd::tl)) let rec partition_equiv (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (pivot:atom) (q:list atom) : Lemma (let open FStar.List.Tot.Base in let hi, lo = partition (bool_of_compare (compare_of_bool (<)) pivot) q in CE.EQ?.eq eq (xsdenote eq m am hi `CE.CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am q)) = let open FStar.Algebra.CommMonoid.Equiv in let open FStar.List.Tot.Base in let f = bool_of_compare (compare_of_bool (<)) pivot in let hi, lo = partition f q in match q with | [] -> CM?.identity m (xsdenote eq m am hi) | hd::tl -> let l1, l2 = partition f tl in partition_equiv eq m am pivot tl; assert (EQ?.eq eq (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (xsdenote eq m am tl)); EQ?.reflexivity eq (xsdenote eq m am l1); EQ?.reflexivity eq (xsdenote eq m am l2); EQ?.reflexivity eq (xsdenote eq m am hi); EQ?.reflexivity eq (xsdenote eq m am lo); if f hd then begin assert (hi == hd::l1 /\ lo == l2); lemma_xsdenote_aux eq m am hd l1; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am l1) (xsdenote eq m am l2); CM?.associativity m (select hd am) (xsdenote eq m am l1) (xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l1) `CM?.mult m` xsdenote eq m am l2) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end else begin assert (hi == l1 /\ lo == hd::l2); lemma_xsdenote_aux eq m am hd l2; CM?.congruence m (xsdenote eq m am hi) (xsdenote eq m am lo) (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); CM?.commutativity m (xsdenote eq m am l1) (select hd am `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (xsdenote eq m am l1 `CM?.mult m` (select hd am `CM?.mult m` xsdenote eq m am l2)) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1); CM?.associativity m (select hd am) (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) ((select hd am `CM?.mult m` xsdenote eq m am l2) `CM?.mult m` xsdenote eq m am l1) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)); CM?.commutativity m (xsdenote eq m am l2) (xsdenote eq m am l1); EQ?.reflexivity eq (select hd am); CM?.congruence m (select hd am) (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1) (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l2 `CM?.mult m` xsdenote eq m am l1)) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)); CM?.congruence m (select hd am) (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2) (select hd am) (xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` (xsdenote eq m am l1 `CM?.mult m` xsdenote eq m am l2)) (select hd am `CM?.mult m` xsdenote eq m am tl); lemma_xsdenote_aux eq m am hd tl; EQ?.symmetry eq (xsdenote eq m am (hd::tl)) (select hd am `CM?.mult m` xsdenote eq m am tl); EQ?.transitivity eq (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select hd am `CM?.mult m` xsdenote eq m am tl) (xsdenote eq m am (hd::tl)) end let rec sort_correct_aux (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (xs:list atom) : Lemma (requires True) (ensures xsdenote eq m am xs `CE.EQ?.eq eq` xsdenote eq m am (sort xs)) (decreases (FStar.List.Tot.Base.length xs)) = let open FStar.Algebra.CommMonoid.Equiv in match xs with | [] -> EQ?.reflexivity eq (xsdenote eq m am []) | pivot::q -> let sort0 : permute = List.Tot.sortWith #int (List.Tot.compare_of_bool (<)) in let sort_eq (l: list atom) : Lemma (sort l == sort0 l) [SMTPat (sort l)] = sortWith_ext (my_compare_of_bool (<)) (List.Tot.compare_of_bool (<)) l in let open FStar.List.Tot.Base in let f:int -> int -> int = compare_of_bool (<) in let hi, lo = partition (bool_of_compare f pivot) q in flatten_correct_aux eq m am (sort lo) (pivot::sort hi); assert (xsdenote eq m am (sort xs) `EQ?.eq eq` CM?.mult m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi))); lemma_xsdenote_aux eq m am pivot (sort hi); EQ?.reflexivity eq (xsdenote eq m am (sort lo)); CM?.congruence m (xsdenote eq m am (sort lo)) (xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` xsdenote eq m am (pivot::sort hi)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)))); CM?.commutativity m (xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` xsdenote eq m am (sort hi)); CM?.associativity m (select pivot am) (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)); EQ?.transitivity eq (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) ((select pivot am `CM?.mult m` xsdenote eq m am (sort hi)) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (xsdenote eq m am (sort lo) `CM?.mult m` (select pivot am `CM?.mult m` xsdenote eq m am (sort hi))) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)))); partition_length (bool_of_compare f pivot) q; sort_correct_aux eq m am hi; sort_correct_aux eq m am lo; EQ?.symmetry eq (xsdenote eq m am lo) (xsdenote eq m am (sort lo)); EQ?.symmetry eq (xsdenote eq m am hi) (xsdenote eq m am (sort hi)); CM?.congruence m (xsdenote eq m am (sort hi)) (xsdenote eq m am (sort lo)) (xsdenote eq m am hi) (xsdenote eq m am lo); assert (EQ?.eq eq (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); EQ?.reflexivity eq (select pivot am); CM?.congruence m (select pivot am) (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo)) (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am (sort hi) `CM?.mult m` xsdenote eq m am (sort lo))) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo))); partition_equiv eq m am pivot q; CM?.congruence m (select pivot am) (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo) (select pivot am) (xsdenote eq m am q); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am hi `CM?.mult m` xsdenote eq m am lo)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); assert (EQ?.eq eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q))); lemma_xsdenote_aux eq m am pivot q; EQ?.symmetry eq (xsdenote eq m am (pivot::q)) (select pivot am `CM?.mult m` (xsdenote eq m am q)); EQ?.transitivity eq (xsdenote eq m am (sort xs)) (select pivot am `CM?.mult m` (xsdenote eq m am q)) (xsdenote eq m am xs); EQ?.symmetry eq (xsdenote eq m am (sort xs)) (xsdenote eq m am xs) #pop-options #push-options "--fuel 0 --ifuel 0" (* Lemmas to be called after a permutation compatible with AC-unification was found *) let smt_reflexivity (#a:Type) (eq:CE.equiv a) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x y) = CE.EQ?.reflexivity eq x let identity_left_smt (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires x == y) (ensures CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) y)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_left (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x:a) : Lemma (CE.EQ?.eq eq x (CE.CM?.mult m (CE.CM?.unit m) x)) = CE.CM?.identity m x; CE.EQ?.symmetry eq (CE.CM?.mult m (CE.CM?.unit m) x) x let identity_right_diff (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (x y:a) : Lemma (requires CE.EQ?.eq eq x y) (ensures CE.EQ?.eq eq (CE.CM?.mult m x (CE.CM?.unit m)) y) = CE.right_identity eq m x; CE.EQ?.transitivity eq (CE.CM?.mult m x (CE.CM?.unit m)) x y /// Dismiss possible vprops goals that might have been created by lemma application. /// These vprops will be instantiated at a later stage; else, Meta-F* will raise an error let rec dismiss_slprops () : Tac unit = match term_as_formula' (cur_goal ()) with | App t _ -> if is_fvar t (`%squash) then () else (dismiss(); dismiss_slprops ()) | _ -> dismiss(); dismiss_slprops () /// Recursively removing trailing empty assertions let rec n_identity_left (n:int) (eq m:term) : Tac unit = if n = 0 then ( apply_lemma (`(CE.EQ?.reflexivity (`#eq))); // Cleaning up, in case a uvar has been generated here. It'll be solved later set_goals []) else ( apply_lemma (`identity_right_diff (`#eq) (`#m)); // Drop the slprops generated, they will be solved later dismiss_slprops (); n_identity_left (n-1) eq m ) /// Helper lemma: If two vprops (as represented by lists of atoms) are equivalent, then their canonical forms /// (corresponding to applying the sort function on atoms) are equivalent let equivalent_sorted (#a:Type) (eq:CE.equiv a) (m:CE.cm a eq) (am:amap a) (l1 l2 l1' l2':list atom) : Lemma (requires sort l1 == sort l1' /\ sort l2 == sort l2' /\ xsdenote eq m am l1 `CE.EQ?.eq eq` xsdenote eq m am l2) (ensures xsdenote eq m am l1' `CE.EQ?.eq eq` xsdenote eq m am l2') = let open FStar.Algebra.CommMonoid.Equiv in sort_correct_aux eq m am l1'; sort_correct_aux eq m am l1; EQ?.symmetry eq (xsdenote eq m am l1) (xsdenote eq m am (sort l1)); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l1')) (xsdenote eq m am l1); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l1) (xsdenote eq m am l2); sort_correct_aux eq m am l2; EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am l2) (xsdenote eq m am (sort l2)); sort_correct_aux eq m am l2'; EQ?.symmetry eq (xsdenote eq m am l2') (xsdenote eq m am (sort l2')); EQ?.transitivity eq (xsdenote eq m am l1') (xsdenote eq m am (sort l2)) (xsdenote eq m am l2') #pop-options /// Finds the position of first occurrence of x in xs. /// This is now specialized to terms and their funny term_eq_old. let rec where_aux (n:nat) (x:term) (xs:list term) : Tac (option nat) (decreases xs) = match xs with | [] -> None | x'::xs' -> if term_eq_old x x' then Some n else where_aux (n+1) x xs' let where = where_aux 0 let fatom (t:term) (ts:list term) (am:amap term) : Tac (exp * list term * amap term) = match where t ts with | Some v -> (Atom v, ts, am) | None -> let vfresh = List.Tot.Base.length ts in let t = norm_term [iota; zeta] t in (Atom vfresh, ts `List.Tot.append` [t], update vfresh t am) /// Transforming a term into the corresponding list of atoms /// If the atomic terms were already present in the map [am], then /// they correspond to the same atoms /// This expects that mult, unit, and t have already been normalized let rec reification_aux (ts:list term) (am:amap term) (mult unit t : term) : Tac (exp * list term * amap term) = let hd, tl = collect_app_ref t in match inspect_unascribe hd, List.Tot.Base.list_unref tl with | Tv_FVar fv, [(t1, Q_Explicit) ; (t2, Q_Explicit)] -> if term_eq_old (pack (Tv_FVar fv)) mult then (let (e1, ts, am) = reification_aux ts am mult unit t1 in let (e2, ts, am) = reification_aux ts am mult unit t2 in (Mult e1 e2, ts, am)) else fatom t ts am | _, _ -> if term_eq_old t unit then (Unit, ts, am) else fatom t ts am /// Performs the required normalization before calling the function above let reification (eq: term) (m: term) (ts:list term) (am:amap term) (t:term) : Tac (exp * list term * amap term) = let mult = norm_term [iota; zeta; delta] (`CE.CM?.mult (`#m)) in let unit = norm_term [iota; zeta; delta] (`CE.CM?.unit (`#m)) in let t = norm_term [iota; zeta] t in reification_aux ts am mult unit t /// Meta-F* internal: Transforms the atom map into a term let rec convert_map (m : list (atom * term)) : term = match m with | [] -> `[] | (a, t)::ps -> let a = pack (Tv_Const (C_Int a)) in (* let t = norm_term [delta] t in *) `((`#a, (`#t)) :: (`#(convert_map ps))) /// `am` is an amap (basically a list) of terms, each representing a value /// of type `a` (whichever we are canonicalizing). This functions converts /// `am` into a single `term` of type `amap a`, suitable to call `mdenote` with *) let convert_am (am : amap term) : term = let (map, def) = am in (* let def = norm_term [delta] def in *) `( (`#(convert_map map), `#def) ) /// Transforms a term representatoin into a term through quotation let rec quote_exp (e:exp) : term = match e with | Unit -> (`Unit) | Mult e1 e2 -> (`Mult (`#(quote_exp e1)) (`#(quote_exp e2))) | Atom n -> let nt = pack (Tv_Const (C_Int n)) in (`Atom (`#nt)) let rec quote_atoms (l:list atom) = match l with | [] -> `[] | hd::tl -> let nt = pack (Tv_Const (C_Int hd)) in (`Cons (`#nt) (`#(quote_atoms tl))) /// Some internal normalization steps to make reflection of vprops into atoms and atom permutation go smoothly. /// We reimplemented sorting/list functions to normalize our uses without normalizing those introduced by the user. let normal_tac_steps = [primops; iota; zeta; delta_only [ `%mdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm]] /// The normalization function, using the above normalization steps let normal_tac (#a:Type) (x:a) : a = FStar.Pervasives.norm normal_tac_steps x /// Helper lemma to establish relation between normalized and initial values let normal_elim (x:Type0) : Lemma (requires x) (ensures normal_tac x) = () exception Result of list atom * list atom * bool * list term /// F* equalities are typed, but the generated type sometimes is a unification variable. /// This helper ensures that such unification variables are not left unresolved, which would lead to an error let close_equality_typ' (t:term) : Tac unit = let f = term_as_formula' t in match f with | Comp (Eq (Some u)) l _ -> if is_uvar u then (unshelve u; exact_with_ref (tc (cur_env()) l)) | _ -> () /// Recursively closing equality types in a given term (usually a unification constraint) let close_equality_typ (t:term) : Tac unit = visit_tm close_equality_typ' t /// Core unification tactic. /// Transforms terms into their atom representations, /// Tries to find a solution to AC-unification, and if so, /// soundly permutes the atom representations before calling the unifier /// to check the validity of the provided solution. /// In the case where SMT rewriting was needed, equalities abduction is performed by instantiating the /// abduction prop unification variable with the corresponding guard /// 09/24: /// /// The tactic internally builds a map from atoms to terms /// and uses the map for reflecting the goal to atoms representation /// During reflection, the tactics engine typechecks the amap, and hence all /// the terms again /// This typechecking of terms is unnecessary, since the terms are coming /// from the goal, and hence are already well-typed /// Worse, re-typechecking them may generate a lot of SMT queries /// And even worse, the SMT queries are discharged in the static context, /// requiring various workarounds (e.g. squash variables for if conditions etc.) /// /// To fix this, we now "name" the terms and use the amap with names /// /// Read through the canon_l_r function for how we do this /// The following three lemmas are helpers to manipulate the goal in canon_l_r [@@ no_subtyping] let inst_bv (#a:Type) (#p:a -> Type0) (#q:Type0) (x:a) (_:squash (p x ==> q)) : Lemma ((forall (x:a). p x) ==> q) = () let modus_ponens (#p #q:Type0) (_:squash p) : Lemma ((p ==> q) ==> q) = () let cut (p q:Type0) : Lemma (requires p /\ (p ==> q)) (ensures q) = () let and_true (p: Type0) : Lemma (requires (p /\ (p ==> True))) (ensures p) = () let solve_implies_true (p: Type0) : Lemma (p ==> True) = () // This exception is raised for failures that should not be considered // hard but should allow postponing the goal instead exception Postpone of string (* NOTE! Redefining boolean disjunction to *not* be short-circuiting, since we cannot use an effectful result as argument of Prims.op_BarBar *) private let bor = op_BarBar private let is_and (t:term) : bool = is_any_fvar t [`%(/\); `%prop_and] private let is_squash (t:term) : bool = is_any_fvar t [`%squash; `%auto_squash] private let is_star (t:term) : bool = is_any_fvar t [`%star; `%VStar] private let is_star_or_unit (t:term) : bool = is_any_fvar t [`%star; `%VStar; `%VUnit] let rec unify_pr_with_true (pr: term) : Tac unit = let hd, tl = collect_app pr in if is_and hd then match tl with | [pr_l, _; pr_r, _] -> unify_pr_with_true pr_l; unify_pr_with_true pr_r | _ -> fail "unify_pr_with_true: ill-formed /\\" else match inspect_unascribe hd with | Tv_Uvar _ _ -> if unify pr (`true_p) then () else begin fail "unify_pr_with_true: could not unify SMT prop with True" end | _ -> if List.Tot.length (free_uvars pr) = 0 then () else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "unify_pr_with_true: some uvars are still there") let elim_and_l_squash (#a #b: Type0) (#goal: Type0) (f: (a -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash a) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash a) = () in f' (elim_impl (FStar.Squash.return_squash h)) let elim_and_r_squash (#a #b: Type0) (#goal: Type0) (f: (b -> Tot (squash goal))) (h: (a /\ b)) : Tot (squash goal) = let f' (x: squash b) : Tot (squash goal) = FStar.Squash.bind_squash x f in let elim_impl (x: squash (a /\ b)) : Tot (squash b) = () in f' (elim_impl (FStar.Squash.return_squash h)) let _return_squash (#a: Type) () (x: a) : Tot (squash a) = FStar.Squash.return_squash x let rec set_abduction_variable_term (pr: term) : Tac term = let hd, tl = collect_app pr in if is_and hd then match tl with | (pr_l, Q_Explicit) :: (pr_r, Q_Explicit) :: [] -> if List.Tot.length (free_uvars pr_r) = 0 then let arg = set_abduction_variable_term pr_l in mk_app (`elim_and_l_squash) [arg, Q_Explicit] else if List.Tot.length (free_uvars pr_l) = 0 then let arg = set_abduction_variable_term pr_r in mk_app (`elim_and_r_squash) [arg, Q_Explicit] else // postpone the goal instead of failing hard, to allow for other goals to solve those uvars raise (Postpone "set_abduction_variable_term: there are still uvars on both sides of l_and") | _ -> fail "set_abduction_variable: ill-formed /\\" else match inspect hd with | Tv_Uvar _ _ -> mk_app (`_return_squash) [`(), Q_Explicit] | _ -> fail "set_abduction_variable: cannot unify" let set_abduction_variable () : Tac unit = let g = cur_goal () in match inspect_unascribe g with | Tv_Arrow b _ -> let pr = b.sort in exact (set_abduction_variable_term pr) | _ -> fail "Not an arrow goal" let canon_l_r (use_smt:bool) (carrier_t:term) //e.g. vprop (eq:term) (m:term) (pr pr_bind:term) (lhs rel rhs:term) : Tac unit = let m_unit = norm_term [iota; zeta; delta] (`(CE.CM?.unit (`#m))) in let m_mult = norm_term [iota; zeta; delta] (`(CE.CM?.mult (`#m))) in let am = const m_unit in (* empty map *) let (r1_raw, ts, am) = reification eq m [] am lhs in let (r2_raw, _, am) = reification eq m ts am rhs in // Encapsulating this in a try/with to avoid spawning uvars for smt_fallback let l1_raw, l2_raw, emp_frame, uvar_terms = try let res = equivalent_lists use_smt (flatten r1_raw) (flatten r2_raw) am in raise (Result res) with | TacticFailure m -> fail m | Result res -> res | _ -> fail "uncaught exception in equivalent_lists" in //So now we have: // am : amap mapping atoms to terms in lhs and rhs // r1_raw : an expression in the atoms language for lhs // r2_raw : an expression in the atoms language for rhs // l1_raw : sorted list of atoms in lhs // l2_raw : sorted list of atoms in rhs // //In particular, r1_raw and r2_raw capture lhs and rhs structurally // (i.e. same associativity, emp, etc.) // //Whereas l1_raw and l2_raw are "canonical" representations of lhs and rhs // (vis xsdenote) //Build an amap where atoms are mapped to names //The type of these names is carrier_t passed by the caller let am_bv : list (atom & namedv & typ) = mapi (fun i (a, _) -> let x = fresh_namedv_named ("x" ^ (string_of_int i)) in (a, x, carrier_t)) (fst am) in let am_bv_term : amap term = map (fun (a, bv, _sort) -> a, pack (Tv_Var bv)) am_bv, snd am in let mdenote_tm (e:exp) : term = mdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term e in let xsdenote_tm (l:list atom) : term = xsdenote_gen m_unit (fun t1 t2 -> mk_app m_mult [(t1, Q_Explicit); (t2, Q_Explicit)]) am_bv_term l in //Get the named representations of lhs, rhs, and their respective sorted versions let lhs_named = mdenote_tm r1_raw in let rhs_named = mdenote_tm r2_raw in let sorted_lhs_named = xsdenote_tm l1_raw in let sorted_rhs_named = xsdenote_tm l2_raw in //We now build an auxiliary goal of the form: // // forall xs. (sorted_lhs_named `rel` sorted_rhs_names) ==> (lhs_names `rel` rhs_named) // // where xs are the fresh names that we introduced earlier let mk_rel (l r:term) : term = mk_app rel [(l, Q_Explicit); (r, Q_Explicit)] in let imp_rhs = mk_rel lhs_named rhs_named in let imp_lhs = mk_rel sorted_lhs_named sorted_rhs_named in let imp = mk_app (pack (Tv_FVar (pack_fv imp_qn))) [(imp_lhs, Q_Explicit); (imp_rhs, Q_Explicit)] in //fold over names and quantify over them let aux_goal = fold_right (fun (_, nv, sort) t -> let nvv = inspect_namedv nv in let b = { ppname = nvv.ppname; uniq = nvv.uniq; qual = Q_Explicit; attrs = []; sort = sort; } in let _, t = close_term b t in let t = pack (Tv_Abs b t) in mk_app (pack (Tv_FVar (pack_fv forall_qn))) [t, Q_Explicit]) am_bv imp in //Introduce a cut with the auxiliary goal apply_lemma (`cut (`#aux_goal)); //After the cut, the goal looks like: A /\ (A ==> G) // where A is the auxiliary goal and G is the original goal (lhs `rel` rhs) split (); //Solving A: focus (fun _ -> //The proof follows a similar structure as before naming was introduced // //Except that this time, the amap is in terms of names, // and hence its typechecking is faster and (hopefully) no SMT involved //Open the forall binders in A, and use the fresh names to build an amap let am = fold_left (fun am (a, _, _sort) -> let b = forall_intro () in let v = binding_to_namedv b in (a, pack (Tv_Var v))::am) [] am_bv, snd am in //Introduce the lhs of implication let b = implies_intro () in //Now the proof is the plain old canon proof let am = convert_am am in let r1 = quote_exp r1_raw in let r2 = quote_exp r2_raw in change_sq (`(normal_tac (mdenote (`#eq) (`#m) (`#am) (`#r1) `CE.EQ?.eq (`#eq)` mdenote (`#eq) (`#m) (`#am) (`#r2)))); apply_lemma (`normal_elim); apply (`monoid_reflect ); let l1 = quote_atoms l1_raw in let l2 = quote_atoms l2_raw in apply_lemma (`equivalent_sorted (`#eq) (`#m) (`#am) (`#l1) (`#l2)); if List.Tot.length (goals ()) = 0 then () else begin norm [primops; iota; zeta; delta_only [`%xsdenote; `%select; `%my_assoc; `%my_append; `%flatten; `%sort; `%my_sortWith; `%my_partition; `%my_bool_of_compare; `%my_compare_of_bool; `%fst; `%__proj__Mktuple2__item___1; `%snd; `%__proj__Mktuple2__item___2; `%CE.__proj__CM__item__unit; `%CE.__proj__CM__item__mult; `%rm; `%CE.__proj__EQ__item__eq; `%req; `%star;] ]; //The goal is of the form G1 /\ G2 /\ G3, as in the requires of equivalent_sorted split (); split (); //Solve G1 and G2 by trefl trefl (); trefl (); //G3 is the lhs of the implication in the auxiliary goal // that we have in our assumptions via b apply (`FStar.Squash.return_squash); exact (binding_to_term b) end); dismiss_slprops(); //Our goal now is A ==> G (where G is the original goal (lhs `rel` rhs)) //Open the forall binders ignore (repeatn (List.Tot.length am_bv) (fun _ -> apply_lemma (`inst_bv))); //And apply modus ponens apply_lemma (`modus_ponens); //Now our goal is sorted_lhs_named `rel` sorted_rhs_named // where the names are replaced with fresh uvars (from the repeatn call above) //So we just trefl match uvar_terms with | [] -> // Closing unneeded prop uvar focus (fun _ -> try apply_lemma (`and_true); split (); if emp_frame then apply_lemma (`identity_left (`#eq) (`#m)) else apply_lemma (`(CE.EQ?.reflexivity (`#eq))); unify_pr_with_true pr; // MUST be done AFTER identity_left/reflexivity, which can unify other uvars apply_lemma (`solve_implies_true) with | TacticFailure msg -> fail ("Cannot unify pr with true: " ^ msg) | e -> raise e ) | l -> if emp_frame then ( apply_lemma (`identity_left_smt (`#eq) (`#m)) ) else ( apply_lemma (`smt_reflexivity (`#eq)) ); t_trefl true; close_equality_typ (cur_goal()); revert (); set_abduction_variable () /// Wrapper around the tactic above /// The constraint should be of the shape `squash (equiv lhs rhs)` let canon_monoid (use_smt:bool) (carrier_t:term) (eq m:term) (pr pr_bind:term) : Tac unit = norm [iota; zeta]; let t = cur_goal () in // removing top-level squash application let sq, rel_xy = collect_app_ref t in // unpacking the application of the equivalence relation (lhs `EQ?.eq eq` rhs) (match rel_xy with | [(rel_xy,_)] -> ( let open FStar.List.Tot.Base in let rel, xy = collect_app_ref rel_xy in if (length xy >= 2) then ( match index xy (length xy - 2) , index xy (length xy - 1) with | (lhs, Q_Explicit) , (rhs, Q_Explicit) -> canon_l_r use_smt carrier_t eq m pr pr_bind lhs rel rhs | _ -> fail "Goal should have been an application of a binary relation to 2 explicit arguments" ) else ( fail "Goal should have been an application of a binary relation to n implicit and 2 explicit arguments" ) ) | _ -> fail "Goal should be squash applied to a binary relation") /// Instantiation of the generic AC-unification tactic with the vprop commutative monoid let canon' (use_smt:bool) (pr:term) (pr_bind:term) : Tac unit = canon_monoid use_smt (pack (Tv_FVar (pack_fv [`%vprop]))) (`req) (`rm) pr pr_bind /// Counts the number of unification variables corresponding to vprops in the term [t] let rec slterm_nbr_uvars (t:term) : Tac int = match inspect_unascribe t with | Tv_Uvar _ _ -> 1 | Tv_App _ _ -> let hd, args = collect_app t in if is_star_or_unit hd then // Only count the number of unresolved slprops, not program implicits slterm_nbr_uvars_argv args else if is_uvar hd then 1 else 0 | Tv_Abs _ t -> slterm_nbr_uvars t | _ -> 0 and slterm_nbr_uvars_argv (args: list argv) : Tac int = fold_left (fun n (x, _) -> n + slterm_nbr_uvars x) 0 args let guard_vprop (v: vprop) : Tot vprop = v let rec all_guards_solved (t: term) : Tac bool = match inspect_unascribe t with | Tv_Abs _ t -> all_guards_solved t | Tv_App _ _ -> let hd, args = collect_app t in if hd `is_fvar` (`%guard_vprop) then slterm_nbr_uvars_argv args = 0 else if not (all_guards_solved hd) then false else List.Tot.fold_left (fun (tac: (unit -> Tac bool)) (tm, _) -> let f () : Tac bool = if all_guards_solved tm then tac () else false in f ) (let f () : Tac bool = true in f) args () | _ -> true let unfold_guard () : Tac bool = if all_guards_solved (cur_goal ()) then begin focus (fun _ -> norm [delta_only [(`%guard_vprop)]]); true end else false let rec term_is_uvar (t: term) (i: int) : Tac bool = match inspect t with | Tv_Uvar i' _ -> i = i' | Tv_App _ _ -> let hd, args = collect_app t in term_is_uvar hd i | _ -> false val solve_can_be_split_for : string -> Tot unit val solve_can_be_split_lookup : unit // FIXME: src/reflection/FStar.Reflection.Basic.lookup_attr only supports fvar attributes, so we cannot directly look up for (solve_can_be_split_for blabla), we need a nullary attribute to use with lookup_attr let rec dismiss_all_but_last' (l: list goal) : Tac unit = match l with | [] | [_] -> set_goals l | _ :: q -> dismiss_all_but_last' q let dismiss_all_but_last () : Tac unit = dismiss_all_but_last' (goals ()) let rec dismiss_non_squash_goals' (keep:list goal) (goals:list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev keep) | hd :: tl -> let f = term_as_formula' (goal_type hd) in match f with | App hs _ -> if is_squash hs then dismiss_non_squash_goals' (hd::keep) tl else dismiss_non_squash_goals' keep tl | _ -> dismiss_non_squash_goals' keep tl let dismiss_non_squash_goals () = let g = goals () in dismiss_non_squash_goals' [] g let rec term_mem (te: term) (l: list term) : Tac bool = match l with | [] -> false | t' :: q -> if te `term_eq_old` t' then true else term_mem te q let rec lookup_by_term_attr' (attr: term) (e: env) (found: list fv) (l: list fv) : Tac (list fv) = match l with | [] -> List.Tot.rev found | f :: q -> let n = inspect_fv f in begin match lookup_typ e n with | None -> lookup_by_term_attr' attr e found q | Some se -> let found' = if attr `term_mem` sigelt_attrs se then f :: found else found in lookup_by_term_attr' attr e found' q end let lookup_by_term_attr (label_attr: term) (attr: term) : Tac (list fv) = let e = cur_env () in let candidates = lookup_attr label_attr e in lookup_by_term_attr' attr e [] candidates let rec bring_last_goal_on_top' (others: list goal) (goals: list goal) : Tac unit = match goals with | [] -> set_goals (List.Tot.rev others) | last :: [] -> set_goals (last :: List.Tot.rev others) | a :: q -> bring_last_goal_on_top' (a :: others) q let bring_last_goal_on_top () = let g = goals () in bring_last_goal_on_top' [] g let rec extract_contexts (lemma_left lemma_right label_attr attr: term) (t: term) : Tac (option (unit -> Tac unit)) = let hd, tl = collect_app t in if is_star hd then match tl with | (t_left, Q_Explicit) :: (t_right, Q_Explicit) :: [] -> let extract_right () : Tac (option (unit -> Tac unit)) = match extract_contexts lemma_left lemma_right label_attr attr t_right with | None -> None | Some f -> Some (fun _ -> apply_lemma lemma_right; dismiss_all_but_last (); f () ) in begin match extract_contexts lemma_left lemma_right label_attr attr t_left with | None -> extract_right () | Some f -> Some (fun _ -> try apply_lemma lemma_left; dismiss_all_but_last (); f () with _ -> begin match extract_right () with | None -> fail "no context on the right either" | Some g -> g () end ) end | _ -> None else let candidates = let hd_fv = match inspect_unascribe hd with | Tv_FVar fv -> Some fv | Tv_UInst fv _ -> Some fv | _ -> None in match hd_fv with | None -> [] | Some hd_fv -> let hd_s' = implode_qn (inspect_fv hd_fv) in let hd_s = pack (Tv_Const (C_String hd_s')) in lookup_by_term_attr label_attr (mk_app attr [hd_s, Q_Explicit]) in if Nil? candidates then None else Some (fun _ -> first (List.Tot.map (fun candidate _ -> apply_lemma (pack (Tv_FVar candidate)) <: Tac unit) candidates); dismiss_non_squash_goals () ) let extract_cbs_contexts = extract_contexts (`can_be_split_congr_l) (`can_be_split_congr_r) (`solve_can_be_split_lookup) (`solve_can_be_split_for) let open_existentials () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [delta_attr [`%__reduce__]]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split) then match tl with | _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match extract_cbs_contexts rhs with | None -> fail "open_existentials: no context found" | Some f -> apply_lemma (`can_be_split_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top () // so that any preconditions for the selected lemma are scheduled for later end | _ -> fail "open_existentials: ill-formed can_be_split" else fail "open_existentials: not a can_be_split goal" | _ -> fail "open_existentials: not a squash goal" let try_open_existentials () : Tac bool = focus (fun _ -> try open_existentials (); true with _ -> false ) (* Solving the can_be_split* constraints, if they are ready to be scheduled A constraint is deemed ready to be scheduled if it contains only one vprop unification variable If so, constraints are stripped to their underlying definition based on vprop equivalence, introducing universally quantified variables when needed. Internal details of the encoding are removed through normalization, before calling the AC-unification tactic defined above *) /// Solves a `can_be_split` constraint let rec solve_can_be_split (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> apply_lemma (`equiv_can_be_split); dismiss_slprops(); // If we have exactly the same term on both side, // equiv_sl_implies would solve the goal immediately or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if rnbr = 0 then apply_lemma (`equiv_sym); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true with | _ -> let opened_some = try_open_existentials () in if opened_some then solve_can_be_split args // we only need args for their number of uvars, which has not changed else false ) else false | _ -> false // Ill-formed can_be_split, should not happen /// Solves a can_be_split_dep constraint let solve_can_be_split_dep (args:list argv) : Tac bool = match args with | [(p, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); dismiss_slprops (); or_else (fun _ -> let b = unify p (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true p (binding_to_term p_bind))); true ) else false | _ -> fail "ill-formed can_be_split_dep" /// Helper rewriting lemma val emp_unit_variant (p:vprop) : Lemma (ensures can_be_split p (p `star` emp)) /// Solves a can_be_split_forall constraint let solve_can_be_split_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> ignore (forall_intro()); apply_lemma (`equiv_can_be_split); dismiss_slprops(); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed can_be_split_forall, should not happen" val solve_can_be_split_forall_dep_for : string -> Tot unit val solve_can_be_split_forall_dep_lookup : unit // FIXME: same as solve_can_be_split_for above let extract_cbs_forall_dep_contexts = extract_contexts (`can_be_split_forall_dep_congr_l) (`can_be_split_forall_dep_congr_r) (`solve_can_be_split_forall_dep_lookup) (`solve_can_be_split_forall_dep_for) let open_existentials_forall_dep () : Tac unit = let e = cur_env () in if Nil? (lookup_attr (`solve_can_be_split_forall_dep_lookup) e) then fail "Tactic disabled: no available lemmas in context"; norm [ delta_only [ `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__unit; `%FStar.Algebra.CommMonoid.Equiv.__proj__CM__item__mult; `%rm; ]; iota; delta_attr [`%__reduce__]; ]; let t0 = cur_goal () in match collect_app t0 with | _ (* squash/auto_squash *) , (t1, Q_Explicit) :: [] -> let hd, tl = collect_app t1 in if hd `is_fvar` (`%can_be_split_forall_dep) then match tl with | _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] | (_, Q_Implicit) (* #a *) :: _ (* cond *) :: _ (* lhs *) :: (rhs, Q_Explicit) :: [] -> begin match inspect_unascribe rhs with | Tv_Abs _ body -> begin match extract_cbs_forall_dep_contexts body with | None -> fail "open_existentials_forall_dep: no candidate" | Some f -> apply_lemma (`can_be_split_forall_dep_trans_rev); dismiss_all_but_last (); split (); focus f; bring_last_goal_on_top (); if Cons? (goals ()) then norm [] end | _ -> fail "open_existentials_forall_dep : not an abstraction" end | _ -> fail "open_existentials_forall_dep : wrong number of arguments to can_be_split_forall_dep" else fail "open_existentials_forall_dep : not a can_be_split_forall_dep goal" | _ -> fail "open_existentials_forall_dep : not a squash/auto_squash goal" let try_open_existentials_forall_dep () : Tac bool = focus (fun _ -> try open_existentials_forall_dep (); true with _ -> false ) /// Solves a can_be_split_forall_dep constraint let rec solve_can_be_split_forall_dep (args:list argv) : Tac bool = match args with | [_; (pr, _); (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in try focus (fun _ -> norm []; let x = forall_intro () in let pr = mk_app pr [(binding_to_term x, Q_Explicit)] in let p_bind = implies_intro () in apply_lemma (`equiv_can_be_split); or_else (fun _ -> flip()) (fun _ -> ()); let pr = norm_term [] pr in or_else (fun _ -> let b = unify pr (`true_p) in if not b then fail "could not unify SMT prop with True"; apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' true pr (binding_to_term p_bind))); true with | Postpone msg -> false | TacticFailure msg -> let opened = try_open_existentials_forall_dep () in if opened then solve_can_be_split_forall_dep args // we only need args for their number of uvars, which has not changed else fail msg | _ -> fail "Unexpected exception in framing tactic" ) else false | _ -> fail "Ill-formed can_be_split_forall_dep, should not happen" /// Solves an equiv_forall constraint let solve_equiv_forall (args:list argv) : Tac bool = match args with | [_; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv_forall, should not happen" /// Solves an equiv constraint let solve_equiv (args:list argv) : Tac bool = match args with | [(t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip ()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "Ill-formed equiv, should not happen" /// Solves a can_be_split_post constraint let solve_can_be_split_post (args:list argv) : Tac bool = match args with | [_; _; (t1, _); (t2, _)] -> let lnbr = slterm_nbr_uvars t1 in let rnbr = slterm_nbr_uvars t2 in if if lnbr + rnbr <= 1 then unfold_guard () else false then ( let open FStar.Algebra.CommMonoid.Equiv in focus (fun _ -> norm[]; let g = _cur_goal () in ignore (forall_intro()); apply_lemma (`equiv_forall_elim); match goals () with | [] -> () | _ -> dismiss_slprops (); ignore (forall_intro()); or_else (fun _ -> apply_lemma (`equiv_refl)) (fun _ -> if lnbr <> 0 && rnbr = 0 then apply_lemma (`equiv_sym); or_else (fun _ -> flip()) (fun _ -> ()); norm [delta_only [ `%__proj__CM__item__unit; `%__proj__CM__item__mult; `%rm; `%__proj__Mktuple2__item___1; `%__proj__Mktuple2__item___2; `%fst; `%snd]; delta_attr [`%__reduce__]; primops; iota; zeta]; canon' false (`true_p) (`true_p))); true ) else false | _ -> fail "ill-formed can_be_split_post" /// Checks whether any of the two terms was introduced during a Steel monadic return let is_return_eq (l r:term) : Tac bool = let nl, al = collect_app l in let nr, ar = collect_app r in is_fvar nl (`%return_pre) || is_fvar nr (`%return_pre) /// Solves indirection equalities introduced by the layered effects framework. /// If these equalities were introduced during a monadic return, they need to be solved
{ "checked_file": "/", "dependencies": [ "Steel.Memory.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.CanonCommMonoidSimple.Equiv.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Set.fsti.checked", "FStar.Reflection.V2.Derived.Lemmas.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Ghost.fsti.checked", "FStar.FunctionalExtensionality.fsti.checked", "FStar.Classical.fsti.checked", "FStar.Algebra.CommMonoid.Equiv.fst.checked" ], "interface_file": false, "source_file": "Steel.Effect.Common.fsti" }
[ { "abbrev": false, "full_module": "FStar.Reflection.V2.Derived.Lemmas", "short_module": null }, { "abbrev": true, "full_module": "FStar.Algebra.CommMonoid.Equiv", "short_module": "CE" }, { "abbrev": false, "full_module": "FStar.Tactics.CanonCommMonoidSimple.Equiv", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": false, "full_module": "Steel.Semantics.Instantiate", "short_module": null }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": true, "full_module": "Steel.Semantics.Hoare.MST", "short_module": "Sem" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.FunctionalExtensionality", "short_module": "FExt" }, { "abbrev": true, "full_module": "Steel.Memory", "short_module": "Mem" }, { "abbrev": false, "full_module": "Steel.Memory", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "Steel.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
fuel: Prims.nat -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.nat", "Prims.op_Equality", "Prims.int", "Prims.unit", "Prims.bool", "FStar.Stubs.Tactics.Types.goal", "Prims.list", "FStar.Pervasives.Native.option", "FStar.Stubs.Reflection.Types.typ", "FStar.Tactics.NamedView.term", "Steel.Effect.Common.solve_indirection_eqs", "Prims.op_Subtraction", "FStar.Tactics.V2.Derived.later", "FStar.Tactics.V2.Derived.trefl", "Steel.Effect.Common.is_return_eq", "FStar.Reflection.V2.Formula.formula", "FStar.Reflection.V2.Formula.term_as_formula'", "FStar.Stubs.Tactics.Types.goal_type", "FStar.Tactics.V2.Derived.goals" ]
[ "recursion" ]
false
true
false
false
false
let rec solve_indirection_eqs (fuel: nat) : Tac unit =
if fuel = 0 then () else match goals () with | [] -> () | hd :: _ -> let f = term_as_formula' (goal_type hd) in match f with | Comp (Eq _) l r -> if is_return_eq l r then later () else trefl (); solve_indirection_eqs (fuel - 1) | _ -> later (); solve_indirection_eqs (fuel - 1)
false